Skip to content

Custom codes

Łukasz Pająk edited this page Aug 3, 2021 · 2 revisions

The initializer file defines custom error codes and error dictionary:

JsonErrors.configure do |config|
  config.custom_codes = {
    general_error: { code: 1001, http_status: 500 },
    not_found: { code: 1002, http_status: 404 },
    database_error: { code: 1003, http_status: 500 },
    parameter_missing: { code: 1010, http_status: 400 },
    validation_failed: { code: 1020, http_status: 422 },
    internal_server_error: { code: 1000, http_status: 500 }
  }

  config.error_dictionary = {
    ActiveRecord::RecordInvalid => :validation_failed,
    ActionController::ParameterMissing => :parameter_missing,
    ActiveRecord::RecordNotFound => :not_found,
    ActiveRecord::ActiveRecordError => :database_error,
    StandardError => :internal_server_error
  }
end

The custom_codes hash assigns the error label to the error code and HTTP status code of the response. So, the error labelled with :general_error will be considered as 1001 code under the HTTP 500 Internal Server Error response. Codes are customizable. They can be either numeric or string.

The error_dictionary hash defines what error classes are connected to which error codes.

You can create different custom codes and connect them to your error classes. Let's say you have authentication and you want to respond with HTTP 403 Forbidden whenever someone is unauthenticated. You can do it 2 ways:

1. By handling custom error class

Add new label to the custom_codes

  unauthenticated: { code: 2001, http_status: 403 }

and your error class to the error_dictionary:

Unauthenticated => :unauthenticated

Then just raise the error while checking the authentication.

Unauthenticated = Class.new(StandardError)

raise Unauthenticated, 'Authentication needed'

2. By raising error by label

Add new label to the custom_codes

  unauthenticated: { code: 2001, http_status: 403 }

Then just raise the error while checking the authentication.

raise JsonErrors::Error.unauthenticated('Authentication needed') 

In both cases you will get the HTTP 403 Forbidden response with JSON formatted body:

{
  "code":2001,
  "message":"Authentication needed"
}
Clone this wiki locally