-
Notifications
You must be signed in to change notification settings - Fork 0
Centralized Error Handling
zenkul edited this page Dec 19, 2024
·
1 revision
This page documents the centralized error handling strategy for our Rails application.
- Maintainability: Clear and organized error definitions.
- Consistency: Uniform error handling and formatting.
- Readability: Easy-to-understand error handling logic.
- Extensibility: Simple addition of new error types.
We use the Errors or could name as AppErrors(App for application name) class in app/lib to manage our error classes.
# app/lib/errors.rb
class errors < StandardError
attr_reader :status_code, :locale_key
def initialize(locale_key = nil, status_code = 500, **kwargs)
@locale_key = locale_key
@status_code = status_code
super(I18n.t(locale_key, **kwargs))
end
def self.define(locale_key, status_code)
new(locale_key, status_code)
end
end
class Errors::UserError
InvalidParams = define('errors.users.invalid_params', 400)
NotFound = define('errors.users.not_found', 404)
# ... other user-related errors
end-
Errors: Parent class for all errors.-
status_code: HTTP status code. -
locale_key: Key for localized error messages. -
define: Creates new error constants.
-
-
Specific Error Classes: Group related errors (e.g.,
UserError).
-
Raise Errors:
raise Errors::UserError::InvalidParams if user.invalid?
-
Rescue Errors: Use
rescue_fromin controllers or grape api:rescue_from StandardError do |e| # or AppErrors later when the app was named error!({ error: e.message }, e.status_code) end
Store localized error messages in YAML files (e.g., config/locales/en.yml):
en:
errors:
users:
invalid_params: "Invalid parameters provided."
not_found: "User not found."- Organized error definitions.
- Consistent error handling with status codes and localization.
- Simplified error rescue in controllers.
- Easy to add new errors.
- Error Logging: For debugging and monitoring.
- More Specific Errors: Fine-grained error types.
- Custom Middleware: Advanced error handling and formatting.