Skip to content

Consolidate try/catch-log-return-default patterns to use ExceptionUtil - #3444

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:exception-util-consolidation
Jul 10, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:exception-util-consolidation

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Jul 10, 2026 •

Copy link
Copy Markdown
Member

Summary

Replace manual try/catch blocks that log and return a default value with ExceptionUtil method calls, reducing boilerplate and routing exception handling through the common tested path.

Converted patterns:

  • LinuxOSProcess.parseAffinityMask — BigInteger hex parse → getLongOrDefault
  • LinuxOperatingSystemNF.getThreadId — symlink read → getIntOrDefault
  • LinuxOperatingSystemJNA.getThreadId — same pattern → getIntOrDefault
  • LinuxFirmware.queryVcGenCmd — date format parse → getOrDefault
  • LinuxCentralProcessor.parseCacheType — enum valueOf → getOrDefault
  • WindowsInternetProtocolStatsFFM — 4 TCP/UDP stats methods → getOrDefault
  • AbstractNetworkIF — getAllNetworkInterfaces and isLocalInterface → getOrDefault/getBooleanOrDefault

Also downgrades logging from ERROR to DEBUG for network interface and IP stats exceptions — these represent transient/environmental conditions, not application errors.

Test plan

  • mvn compile passes for oshi-common, oshi-core, oshi-core-ffm
  • mvn test passes for oshi-common, oshi-core-ffm, oshi-benchmark
  • mvn spotless:apply, checkstyle:check, forbiddenapis:check, javadoc:javadoc all pass

Summary by CodeRabbit

  • Bug Fixes

    • Improved resilience when collecting network, processor, firmware, process, thread, and Windows connection statistics.
    • Added consistent fallback behavior when system values are unavailable or cannot be parsed.
    • Preserved diagnostic logging for failed system-data retrievals.
  • Documentation

    • Updated the changelog with the latest bug fixes and improvements.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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: 82fb55e3-a93b-4a23-8384-42869e538931

📥 Commits

Reviewing files that changed from the base of the PR and between d58f48b and bdca83a.

📒 Files selected for processing (8)
  • CHANGELOG.md
  • oshi-common/src/main/java/oshi/hardware/common/AbstractNetworkIF.java
  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxFirmware.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/nativefree/LinuxOperatingSystemNF.java
  • oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsInternetProtocolStatsFFM.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystemJNA.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (13)
  • GitHub Check: CodeRabbit / Review
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, windows-latest
  • GitHub Check: Test JDK 26, macos-latest
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (4)
📚 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/hardware/common/platform/linux/LinuxCentralProcessor.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java
  • oshi-common/src/main/java/oshi/hardware/common/AbstractNetworkIF.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/nativefree/LinuxOperatingSystemNF.java
  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxFirmware.java
📚 Learning: 2026-04-12T19:34:56.879Z
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:34:56.879Z
Learning: In OSHI’s Java platform implementations, `PhysicalProcessor.getEfficiency()` / `EfficiencyClass` follow the same convention as Windows `PROCESSOR_RELATIONSHIP.EfficiencyClass`: a *higher* numeric efficiency class value represents *greater performance* and *less efficiency* (typically P-cores higher than E-cores). When reviewing, do not treat cases where P-cores are assigned higher efficiency/class values as a bug—this is intentional cross-platform consistency.

Applied to files:

  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
📚 Learning: 2026-07-06T19:25:59.225Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3432
File: oshi-common/src/main/java/oshi/util/ExceptionUtil.java:26-56
Timestamp: 2026-07-06T19:25:59.225Z
Learning: In this repo’s SLF4J 1.x-compatible logging code, do not flag cases where a logger call uses SLF4J 1.6+ implicit-cause handling—e.g., `log.error("...{}", value, t)` (or similar with a single `{}` placeholder) where `t` is passed as the final/trailing argument. SLF4J will attach `t` as the log event’s cause with the full stack trace; this is equivalent to SLF4J 2.x’s fluent `atLevel(...).setCause(t).log(...)` and is intentionally used to preserve SLF4J 1.x runtime compatibility.

Applied to files:

  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java
  • oshi-common/src/main/java/oshi/hardware/common/AbstractNetworkIF.java
  • oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsInternetProtocolStatsFFM.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/nativefree/LinuxOperatingSystemNF.java
  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxFirmware.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystemJNA.java
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).

Applied to files:

  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystemJNA.java
🔇 Additional comments (9)
CHANGELOG.md (1)

8-8: LGTM!

oshi-common/src/main/java/oshi/hardware/common/AbstractNetworkIF.java (2)

29-29: LGTM!

Also applies to: 154-163


154-157: 🎯 Functional Correctness

No change needed: the 4-parameter overloads already default to DEBUG. ExceptionUtil.getOrDefault(..., Logger, String) and getBooleanOrDefault(..., Logger, String) delegate to Level.DEBUG, so the calls in AbstractNetworkIF match the intended logging level.

			> Likely an incorrect or invalid review comment.
oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java (1)

36-36: LGTM!

Also applies to: 296-297

oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxFirmware.java (1)

17-17: LGTM!

Also applies to: 130-132

oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java (1)

35-35: LGTM!

Also applies to: 290-290

oshi-common/src/main/java/oshi/software/common/os/linux/nativefree/LinuxOperatingSystemNF.java (1)

16-16: LGTM!

Also applies to: 102-106

oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystemJNA.java (1)

30-30: LGTM!

Also applies to: 146-149

oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsInternetProtocolStatsFFM.java (1)

22-22: LGTM!

Also applies to: 40-59


📝 Walkthrough

Walkthrough

The changes replace several explicit try/catch-and-default patterns with ExceptionUtil wrappers across network interface, Linux parsing and thread ID, and Windows network statistics code. Existing fallback values and logging behavior are retained, and the changelog records the consolidation.

Changes

ExceptionUtil consolidation

Layer / File(s) Summary
Network interface exception handling
oshi-common/src/main/java/oshi/hardware/common/AbstractNetworkIF.java, CHANGELOG.md
Network interface enumeration and locality checks use ExceptionUtil defaults for socket failures; the changelog records the refactoring.
Linux value parsing defaults
oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java, oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxFirmware.java, oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java
Cache type, firmware date, and affinity mask parsing use ExceptionUtil fallback helpers.
Linux thread ID fallbacks
oshi-common/src/main/java/oshi/software/common/os/linux/nativefree/LinuxOperatingSystemNF.java, oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystemJNA.java
Thread ID retrieval uses ExceptionUtil when symbolic-link reads or parsing fail.
Windows network statistics defaults
oshi-core-ffm/src/main/java/oshi/software/os/windows/WindowsInternetProtocolStatsFFM.java
TCP and UDP statistics getters use ExceptionUtil, retaining null results and failure logging.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

  • oshi/oshi#3272: Refactors local try/catch default handling to use ExceptionUtil.
  • oshi/oshi#3355: Centralizes FFM internet protocol statistics exception handling.
  • oshi/oshi#3432: Updates ExceptionUtil logging internals for broader logger compatibility.

Poem

I’m a bunny with defaults tucked tight,
Catching exceptions and keeping things light.
From Linux paths to Windows’ streams,
ExceptionUtil now tidies the seams.
Hop, hop—cleaner code in sight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 accurately summarizes the main change: replacing try/catch-return-default patterns with ExceptionUtil.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@codecov

codecov Bot commented Jul 10, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.33333% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.38%. Comparing base (d58f48b) to head (bdca83a).

Files with missing lines Patch % Lines
...shi/software/os/linux/LinuxOperatingSystemJNA.java 0.00% 3 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3444      +/-   ##
============================================
+ Coverage     68.21%   74.38%   +6.16%     
  Complexity       76       76              
============================================
  Files           580      580              
  Lines         21969    21945      -24     
  Branches       3670     3670              
============================================
+ Hits          14987    16323    +1336     
+ Misses         5139     3582    -1557     
- Partials       1843     2040     +197     
Flag Coverage Δ
freebsd 26.84% <33.33%> (+0.02%) ⬆️
linux 31.38% <61.11%> (+0.03%) ⬆️
macos 31.76% <33.33%> (-0.01%) ⬇️
openbsd 26.35% <33.33%> (+0.04%) ⬆️
solaris 28.27% <33.33%> (?)
windows 39.71% <55.55%> (+0.02%) ⬆️

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

☔ View full report in Codecov by Harness.
📢 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.

@dbwiddis
dbwiddis merged commit 4ff73e8 into oshi:master Jul 10, 2026
20 checks passed
@dbwiddis
dbwiddis deleted the exception-util-consolidation branch July 19, 2026 04:58
dbwiddis added a commit that referenced this pull request Jul 26, 2026
PR #3444 consolidated the try/catch-log-return-default pattern onto
ExceptionUtil, but it only reached part of the codebase. A sweep of every
`catch (Throwable)` in main source turns up 47 remaining blocks that log a
message needing no arguments beyond the exception itself, which the existing
helpers already handle with no API change.

This converts 36 of them:

- 21 to ExceptionUtil.getOrDefault / get{Int,Long,Boolean,Double}OrDefault /
  getOptionalInt / runOrLog
- 15 to ForeignFunctions.callInArena{,Int,Long,Double,Boolean}OrDefault, where
  the body already opened a confined arena

The remaining 11 cannot become lambdas, all for the same reason: the try body
assigns locals declared outside it.

- 7 are static-initializer library-binding blocks (AdlUtilFFM, NvmlFunctions,
  SystemdFunctions, UdevFunctions, LinuxLibcFunctions, Kstat2Functions,
  DxgiFFM), each binding 5-11 method handles into enclosing locals.
- MacDisplayFFM and WindowsCentralProcessorFFM assign locals read after the try.
- IWbemLocatorFFM and IWbemServicesFFM free a BSTR in a finally block that is
  assigned inside the try.

Sites logging `("...: {}", t.getMessage())` now also attach the throwable as the
SLF4J cause, so those lines gain a stack trace. That is inherent to the
ExceptionUtil contract and already true of the call sites converted in #3444;
this makes the rest consistent.

Also fixes a pre-existing fully-qualified `oshi.util.LogLevel.WARN` in
FreeBsdOSProcessFFM.

Verified with a clean full-reactor build and a live run of the FFM provider on
macOS covering the restructured paths: disk stores, file stores, network
interfaces, displays, CPU ticks, processor identifier and power sources.
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