Class: Junkfood::Rack::ErrorHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/junkfood/rack/error.rb

Overview

Rack Middleware to catch exceptions, then transform the exceptions into serialized JSON objects to be returned to the caller.

If this middleware catches an Exception, a rack request would be returned with an HTTP status code, a json mime-type in the headers, and JSON string as the response body.

The HTTP status code will be 500 by default.

The JSON object returned would have ‘type’, ‘code’ and ‘message’ fields.

  • ‘type’ will always be ‘Error’.

  • ‘code’ will be the class name of the caught exception, or a customized value.

  • ‘message’ will be the message attribute of the caught exception, or a specifically set customized message.

The developer can customize the HTTP status code, error code and error message via the constructor. Individually, or all at once.

For example:

error_map = {
  'UnauthorizedException' => {
    'status_code' => 401,
    'code' => 'Unauthorized',
    'message' => 'The request did not have the required authorization'
  }
}
use Junkfood::Rack::ErrorHandler, error_map

When the ‘UnauthorizedException’ error is caught, the middleware will return a rack response with a 401 HTTP status code, a code with ‘Unauthorized’, and the given custom error message.

Constant Summary collapse

DEFAULT_STATUS_CODE =

The default HTTP status code for caught errors.

500.freeze
CONTENT_TYPE =

Header to set the content type of error response

'Content-Type'.freeze
JSON_CONTENT_TYPE =

Json’s content type value for the content type header.

'application/json'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, mapping = {}) ⇒ ErrorHandler

Returns a new instance of ErrorHandler.

Parameters:

  • app

    the rest of the rack stack

  • mapping (defaults to: {})

    the mapping of Exceptions to Error codes and messages.



73
74
75
76
# File 'lib/junkfood/rack/error.rb', line 73

def initialize(app, mapping={})
  @app = app
  @mapping = mapping
end

Instance Method Details

#call(env) ⇒ Object

Returns a received rack response, or a generated JSON error in the response body with a custom status code.

Parameters:

  • env

    the rack environment.

Returns:

  • a received rack response, or a generated JSON error in the response body with a custom status code.



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/junkfood/rack/error.rb', line 83

def call(env)
  return @app.call(env)
rescue Exception => e
  map = @mapping[e.class.name] || {}
  error = {
    'type' => 'Error',
    'code' => map['code'] || e.class.name,
    'message' => map['message'] || e.message
  }
  
  return [
    map['status_code'] ? map['status_code'].to_i : DEFAULT_STATUS_CODE,
    { CONTENT_TYPE => JSON_CONTENT_TYPE },
    [error.to_json]]
end