Class: SenorArmando::Rack::ExceptionHandler
- Inherits:
-
Object
- Object
- SenorArmando::Rack::ExceptionHandler
- Includes:
- Goliath::Rack::Validator
- Defined in:
- lib/senor_armando/rack/exception_handler.rb
Overview
Middleware to rescue validation errors and send them up the chain as normal non-200 responses
Class Method Summary collapse
- .error_response(err, headers = {}) ⇒ Object
-
.safely(env, headers = {}) ⇒ Object
Execute a block of code safely.
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app) ⇒ ExceptionHandler
constructor
A new instance of ExceptionHandler.
Constructor Details
#initialize(app) ⇒ ExceptionHandler
Returns a new instance of ExceptionHandler.
8 9 10 |
# File 'lib/senor_armando/rack/exception_handler.rb', line 8 def initialize(app) @app = app end |
Class Method Details
.error_response(err, headers = {}) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/senor_armando/rack/exception_handler.rb', line 21 def self.error_response err, headers={} headers.merge!({ 'Content-Type' => "application/json", 'X-Error-Message' => err., 'X-Error-Detail' => err.description, }) headers.delete('Content-Length') body = { "error" => err.class.to_s.gsub(/.*::/,""), "message" => [err., err.description].compact.join(": "), "status" => err.status_code } [err.status_code, headers, body.to_json] end |
.safely(env, headers = {}) ⇒ Object
Execute a block of code safely.
If the block raises any exception that derives from Goliath::Validation::Error (see specifically those in goliath/validation/standard_http_errors.rb), it will be turned into the corresponding 4xx response with a corresponding message.
If the block raises any other kind of error, we log it and return a less-communicative 500 response.
59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/senor_armando/rack/exception_handler.rb', line 59 def self.safely(env, headers={}) begin yield rescue Goliath::Validation::Error => err error_response(err, headers) rescue Exception => err env.logger.error(err.) env.logger.error(err.backtrace.join("\n")) puts(err.) puts(err.backtrace.join("\n")) error_response(Goliath::Validation::InternalServerError.new('Internal Server Error'), headers) end end |
Instance Method Details
#call(env) ⇒ Object
12 13 14 15 16 |
# File 'lib/senor_armando/rack/exception_handler.rb', line 12 def call(env) self.class.safely(env) do @app.call(env) end end |