Skip to content

Add ExceptionUtil to reduce repetitive exception handling - #3272

Merged
dbwiddis merged 2 commits into
masterfrom
feature/exception-util
May 19, 2026
Merged

dbwiddis merged 2 commits into
masterfrom
feature/exception-util

Conversation

@dbwiddis

@dbwiddis dbwiddis commented May 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Introduces oshi.util.ExceptionUtil — a utility class that consolidates the repetitive try/catch/return-default pattern used extensively in FFM native call wrappers.

Problem

The codebase has 278 catch (Throwable) blocks, almost all in the FFM module, following the same pattern:

try {
    return (int) handle.invokeExact(args);
} catch (Throwable t) {
    LOG.debug("X failed: {}", t.getMessage());
    return -1;
}

This creates significant duplication (~760 lines of boilerplate) and makes the error-handling paths untestable.

Solution

ExceptionUtil provides functional interfaces and utility methods:

  • getOrDefault(ThrowingSupplier<T>, T) — silent variant
  • getOrDefault(ThrowingSupplier<T>, T, Logger, String) — logging variant
  • getIntOrDefault, getLongOrDefault, getBooleanOrDefault, getDoubleOrDefault — primitive variants
  • getOptional, getOptionalInt, getOptionalLong — Optional-returning variants
  • runSilently, runOrLog — void operation variants

Before:

public static int deviceGetCount(MemorySegment countSeg) {
    try {
        return (int) nvmlDeviceGetCount_v2.invokeExact(countSeg);
    } catch (Throwable t) {
        return -1;
    }
}

After:

public static int deviceGetCount(MemorySegment countSeg) {
    return ExceptionUtil.getIntOrDefault(() -> (int) nvmlDeviceGetCount_v2.invokeExact(countSeg), -1);
}

Changes

  • New: oshi-common/.../util/ExceptionUtil.java — the utility class
  • New: oshi-common/.../util/ExceptionUtilTest.java — 30 test cases
  • Refactored: NvmlFunctions.java (13 catch blocks → one-liners)
  • Refactored: CoreFoundation.java (26 catch blocks → one-liners)
  • Refactored: IOKit.java (18 catch blocks → one-liners)

Net: ~400 lines of boilerplate eliminated in this PR. The same pattern can be applied to the remaining ~220 catch(Throwable) blocks in follow-up PRs.

Testing

  • ExceptionUtilTest covers all methods with success, exception, and error (Throwable) paths
  • oshi-common full test suite passes
  • Both oshi-common and oshi-core-ffm compile cleanly

Summary by CodeRabbit

  • Refactor
    • Centralized exception handling via a new utility so native/system modules consistently return safe defaults (or empty optionals) and avoid propagating errors.
  • Tests
    • Added tests validating default-returning, optional-returning, and silent/logging behaviors to ensure consistent fallback behavior across failure scenarios.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5af31571-0035-4f5e-b598-17d1374dbfec

📥 Commits

Reviewing files that changed from the base of the PR and between ace1df9 and 4614972.

📒 Files selected for processing (1)
  • oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java
📜 Recent review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: JMH Benchmarks, macos-latest

📝 Walkthrough

Walkthrough

Adds a new thread-safe ExceptionUtil utility (throwing functional interfaces, default/optional wrappers, and runnable helpers) and updates NVML, CoreFoundation, and IOKit FFM bindings to use these helpers instead of scattered try/catch blocks.

Changes

Exception Utility and Refactoring

Layer / File(s) Summary
Exception utility: interfaces and helpers
oshi-common/src/main/java/oshi/util/ExceptionUtil.java
Introduces ExceptionUtil with nested throwing functional interfaces and typed primitive specializations, plus overloaded helpers: default-returning (getOrDefault, getIntOrDefault, getLongOrDefault, getBooleanOrDefault, getDoubleOrDefault), optional wrappers (getOptional, getOptionalInt, getOptionalLong), and runnable helpers (runSilently, runOrLog) with logging variants.
Exception utility: comprehensive test coverage
oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java
Adds JUnit 5 tests covering success and failure (Exception/Error) paths for default-returning helpers, optional wrappers, runnable helpers, logging overloads, and an edge case for collection defaults.
NVML bindings: adopt exception utility
oshi-core-ffm/src/main/java/oshi/ffm/common/NvmlFunctions.java
Replaces init, shutdown, and device accessor try/catch blocks with ExceptionUtil.getIntOrDefault(...) calls returning -1 on failure; init/shutdown log formatted failure messages.
CoreFoundation wrapper: adopt exception utility
oshi-core-ffm/src/main/java/oshi/ffm/mac/CoreFoundation.java
Refactors numerous CF wrapper methods (CFTypeRef, CFNumberRef, CFBooleanRef, CFArrayRef, CFDataRef, CFDictionaryRef, CFStringRef, CFLocale, CFDateFormatter) to use ExceptionUtil helpers and runSilently, preserving prior fallback defaults on failure.
IOKit wrapper: adopt exception utility
oshi-core-ffm/src/main/java/oshi/ffm/mac/IOKit.java
Refactors IOObject, IOIterator, IORegistryEntry, CF property factory/search and CF property accessors to use ExceptionUtil default-return helpers and runSilently for CFRelease, replacing inline try/catch blocks.

🎯 3 (Moderate) | ⏱️ ~25 minutes

"I'm a rabbit with a gentle hop,
Wrapping throws so calls won't drop.
Defaults returned with quiet cheer,
Native faults no longer smear,
Hooray—safe calls from far and near!" 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.78% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: introducing ExceptionUtil to reduce repetitive exception handling across the codebase.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/exception-util

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
oshi-common/src/main/java/oshi/util/ExceptionUtil.java (1)

102-109: ⚡ Quick win

Preserve stack traces in debug logging overloads.

The current logging calls at Line 106 and in the other 8 overloads drop the exception stack trace by only passing t.getMessage() to the logger. Apply the fix below to preserve the full stack trace, which is essential for diagnosing failures in native/FFM code paths:

Proposed patch
-        } catch (Throwable t) {
-            log.debug(msg, t.getMessage());
+        } catch (Throwable t) {
+            log.debug(msg, t.getMessage(), t);
             return defaultValue;
         }

Apply the same change to all logging overloads in the class (Lines 106, 140, 174, 209, 244, 262, 280, 298, and 327).

This follows the SLF4J best practice: when a Throwable is the final argument in a log call, SLF4J automatically appends the full stack trace while still formatting any message placeholders with the preceding arguments.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@oshi-common/src/main/java/oshi/util/ExceptionUtil.java` around lines 102 -
109, The debug log calls in ExceptionUtil (e.g., getOrDefault(ThrowingSupplier)
and the other overloads referenced) currently pass t.getMessage(), which drops
the stack trace; change each log.debug(...) to pass the Throwable as the last
argument (for example log.debug(msg, t)) so SLF4J will append the full stack
trace while preserving message formatting; apply this same adjustment to all
overloads in the class (the methods around the reported locations including the
overloads at the other nine spots) to ensure full exception details are logged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@oshi-common/src/main/java/oshi/util/ExceptionUtil.java`:
- Around line 102-109: The debug log calls in ExceptionUtil (e.g.,
getOrDefault(ThrowingSupplier) and the other overloads referenced) currently
pass t.getMessage(), which drops the stack trace; change each log.debug(...) to
pass the Throwable as the last argument (for example log.debug(msg, t)) so SLF4J
will append the full stack trace while preserving message formatting; apply this
same adjustment to all overloads in the class (the methods around the reported
locations including the overloads at the other nine spots) to ensure full
exception details are logged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 13b51a02-80a9-41d7-861c-a63769d1248a

📥 Commits

Reviewing files that changed from the base of the PR and between 2baecc8 and 33553c7.

📒 Files selected for processing (5)
  • oshi-common/src/main/java/oshi/util/ExceptionUtil.java
  • oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java
  • oshi-core-ffm/src/main/java/oshi/ffm/common/NvmlFunctions.java
  • oshi-core-ffm/src/main/java/oshi/ffm/mac/CoreFoundation.java
  • oshi-core-ffm/src/main/java/oshi/ffm/mac/IOKit.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: JMH Benchmarks, macos-latest
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/util/ExceptionUtil.java
🔇 Additional comments (4)
oshi-core-ffm/src/main/java/oshi/ffm/common/NvmlFunctions.java (1)

23-24: LGTM!

Also applies to: 158-159, 168-169, 179-179, 190-191, 203-203, 214-214, 225-226, 237-237, 249-250, 261-261, 273-274, 285-285

oshi-core-ffm/src/main/java/oshi/ffm/mac/CoreFoundation.java (1)

43-44: LGTM!

Also applies to: 111-111, 129-129, 138-138, 154-154, 162-162, 195-203, 215-223, 235-243, 255-263, 275-283, 295-303, 327-327, 351-351, 364-364, 388-388, 400-400, 412-418, 443-443, 455-455, 469-470, 492-492, 514-525, 536-559, 577-578, 600-607, 618-619

oshi-core-ffm/src/main/java/oshi/ffm/mac/IOKit.java (1)

39-40: LGTM!

Also applies to: 72-72, 79-84, 97-100, 126-135, 142-151, 158-169, 176-187, 194-205, 212-215, 222-232, 239-245, 250-264, 268-287, 290-309, 312-331, 334-350, 354-368, 407-407

oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java (1)

1-281: LGTM!

@codecov

codecov Bot commented May 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 74.52%. Comparing base (19c9a0c) to head (4614972).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3272      +/-   ##
============================================
- Coverage     74.56%   74.52%   -0.05%     
  Complexity       73       73              
============================================
  Files           406      407       +1     
  Lines         16047    16103      +56     
  Branches       2554     2554              
============================================
+ Hits          11965    12000      +35     
- Misses         2602     2614      +12     
- Partials       1480     1489       +9     
Flag Coverage Δ
linux 38.99% <100.00%> (+0.21%) ⬆️
macos 39.63% <100.00%> (+0.21%) ⬆️
windows 47.42% <100.00%> (+0.05%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Introduce oshi.util.ExceptionUtil with functional interfaces (ThrowingSupplier,
ThrowingIntSupplier, ThrowingLongSupplier, ThrowingBooleanSupplier,
ThrowingDoubleSupplier, ThrowingRunnable) and utility methods that consolidate
the try/catch/return-default pattern used extensively in FFM native call wrappers.

Refactor three of the most repetitive FFM files as demonstration:
- NvmlFunctions.java: 13 catch blocks reduced to one-liners
- CoreFoundation.java: 26 catch blocks reduced to one-liners
- IOKit.java: 18 catch blocks reduced to one-liners

This eliminates ~400 lines of boilerplate while preserving identical behavior.
The ExceptionUtil class is fully tested with 30 test cases covering success paths,
exception paths, error paths, and edge cases.

The same pattern can be applied to the remaining ~220 catch(Throwable) blocks
in the FFM module in follow-up commits.
@dbwiddis
dbwiddis force-pushed the feature/exception-util branch from 33553c7 to ace1df9 Compare May 19, 2026 17:22
Cover the return supplier.getAsFoo() line in getIntOrDefault,
getLongOrDefault, getBooleanOrDefault, and getDoubleOrDefault
logging variants that were missing test coverage.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant