Skip to content

fix: replace bare except blocks with specific exception types#1591

Open
giwaov wants to merge 1 commit intogenlayerlabs:mainfrom
giwaov:fix/313-improve-error-handling
Open

fix: replace bare except blocks with specific exception types#1591
giwaov wants to merge 1 commit intogenlayerlabs:mainfrom
giwaov:fix/313-improve-error-handling

Conversation

@giwaov
Copy link
Copy Markdown

@giwaov giwaov commented Apr 8, 2026

Summary

Replaces all bare \except:\ blocks in the backend with specific exception types to prevent silently swallowing unexpected errors like \KeyboardInterrupt, \SystemExit, or \MemoryError.

Changes

File Before After Rationale
\consensus/worker_service.py\ \except:\ \except (psutil.Error, OSError):\ Only process metric collection errors should be ignored
\database_handler/transactions_processor.py\ \except:\ \except (ValueError, TypeError):\ Address checksum conversion only fails on invalid input
\
ode/create_nodes/providers.py\ \except:\ \except (OSError, ValueError):\ Socket/port errors are the expected failures
\protocol_rpc/fastapi_endpoint_generator.py\ \except:\ \except Exception:\ Rollback cleanup should not propagate but should not catch \BaseException\
\migration/02aa0c34a463_*.py\ \except:\ \except (json.JSONDecodeError, TypeError):\ JSON parsing has specific failure modes

Related Issue

Contributes to #313

Summary by CodeRabbit

  • Bug Fixes
    • Improved exception handling across backend services to catch only specific error types rather than suppressing all exceptions, enhancing error visibility and system reliability while preventing unexpected failures from being masked during operations.

Replace all bare 'except:' blocks in the backend with specific
exception types to avoid silently swallowing unexpected errors
like KeyboardInterrupt, SystemExit, or MemoryError.

Changes:
- worker_service.py: catch (psutil.Error, OSError) for process metrics
- transactions_processor.py: catch (ValueError, TypeError) for address
  checksum conversion
- providers.py: catch (OSError, ValueError) for socket connection check
- fastapi_endpoint_generator.py: catch Exception for rollback errors
- migration script: catch (json.JSONDecodeError, TypeError) for JSON
  parsing

Contributes to genlayerlabs#313
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 8, 2026

📝 Walkthrough

Walkthrough

This PR systematically tightens exception handling across five backend files by replacing broad bare except: clauses with specific exception type catching. Each modification targets particular exception classes (psutil.Error, OSError, json.JSONDecodeError, TypeError, ValueError, Exception) rather than suppressing all exceptions, allowing unexpected errors to propagate.

Changes

Cohort / File(s) Summary
Health Check & Metrics
backend/consensus/worker_service.py
Narrowed exception handling in health check's metrics collection from blanket except: to except (psutil.Error, OSError) for CPU/memory operations.
Database & Persistence Layer
backend/database_handler/migration/versions/02aa0c34a463_validator_config_string_to_jsonb.py, backend/database_handler/transactions_processor.py
Tightened exception handling for JSON parsing (except (json.JSONDecodeError, TypeError)) and address checksum normalization (except (ValueError, TypeError)) to allow unexpected exceptions to propagate.
Node Provider Detection
backend/node/create_nodes/providers.py
Restricted is_ollama_available() exception handling from catch-all to except (OSError, ValueError) for availability checks.
RPC Endpoint Handling
backend/protocol_rpc/fastapi_endpoint_generator.py
Refined database rollback error suppression in handle_method from except: to except Exception: to allow non-Exception throwables to propagate.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • #1435: Modifies the same health_check function in worker_service.py, directly overlapping with this PR's changes in that file.
  • #1439: Also modifies health_check logic in worker_service.py, introducing generic error retries alongside exception handling adjustments.

Suggested labels

run-tests

Poem

🐰 Whiskers twitched with glee today,
Bare exceptions swept away!
Specific catches, clean and bright,
Unexpected errors see the light!
Code now catches just what's right!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: replacing bare except blocks with specific exception types across the backend.
Description check ✅ Passed The PR description covers most required sections: summary, changes, and related issue. However, it lacks the testing, decisions, and user-facing release notes sections from the template.

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

✨ 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 and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
backend/database_handler/transactions_processor.py (1)

901-904: Pattern at line 903 is correct and complete.

The change to except (ValueError, TypeError): correctly captures the two exceptions that to_checksum_address() can raise:

  • TypeError: when input is not a string or bytes (e.g., None, int)
  • ValueError: when input is a string/bytes but not a valid Ethereum address (wrong length, non-hex, invalid EIP-55 checksum)

However, note that line 1385 in the same file is incomplete — it catches only ValueError and will miss TypeError:

except ValueError:  # Line 1385 - should also catch TypeError
    checksum_address = address

Consider updating line 1385 to match the pattern: except (ValueError, TypeError):. Lines 922, 1422, and 1454 use overly broad Exception catches, which work but are less precise.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/database_handler/transactions_processor.py` around lines 901 - 904,
One occurrence of checksum address conversion uses except ValueError only when
calling self.web3.to_checksum_address(address) (the checksum_address assignment
block) which will miss TypeError cases; change that except ValueError to except
(ValueError, TypeError) to match the earlier correct pattern used where
checksum_address = self.web3.to_checksum_address(address) is guarded, and while
here you’re editing the except clause for checksum_address ensure any other
broad except Exception blocks around checksum/address conversion (the handlers
near the other checksum_address assignments) are reviewed and narrowed where
possible (prefer catching ValueError and TypeError specifically).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@backend/database_handler/transactions_processor.py`:
- Around line 901-904: One occurrence of checksum address conversion uses except
ValueError only when calling self.web3.to_checksum_address(address) (the
checksum_address assignment block) which will miss TypeError cases; change that
except ValueError to except (ValueError, TypeError) to match the earlier correct
pattern used where checksum_address = self.web3.to_checksum_address(address) is
guarded, and while here you’re editing the except clause for checksum_address
ensure any other broad except Exception blocks around checksum/address
conversion (the handlers near the other checksum_address assignments) are
reviewed and narrowed where possible (prefer catching ValueError and TypeError
specifically).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c7749154-3417-4d58-aee5-5dfd14d981d9

📥 Commits

Reviewing files that changed from the base of the PR and between cd554a6 and ca2b5d3.

📒 Files selected for processing (5)
  • backend/consensus/worker_service.py
  • backend/database_handler/migration/versions/02aa0c34a463_validator_config_string_to_jsonb.py
  • backend/database_handler/transactions_processor.py
  • backend/node/create_nodes/providers.py
  • backend/protocol_rpc/fastapi_endpoint_generator.py

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