Skip to content

Centralized Error Handling

zenkul edited this page Dec 19, 2024 · 1 revision

Centralized Error Handling in Rails

This page documents the centralized error handling strategy for our Rails application.

Goals

  • 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.

Implementation

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

Components

  • 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).

Usage

  1. Raise Errors:

    raise Errors::UserError::InvalidParams if user.invalid?
  2. Rescue Errors: Use rescue_from in 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

Locale Files

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."

Benefits

  • Organized error definitions.
  • Consistent error handling with status codes and localization.
  • Simplified error rescue in controllers.
  • Easy to add new errors.

Future Considerations

  • Error Logging: For debugging and monitoring.
  • More Specific Errors: Fine-grained error types.
  • Custom Middleware: Advanced error handling and formatting.
Clone this wiki locally