Created
October 20, 2020 15:17
-
-
Save coorasse/c4b54d201218ab2b6f42ec985490b2d1 to your computer and use it in GitHub Desktop.
A Rack Middleware to catch errors in Rails API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ActionDispatch | |
class JsonApiPublicExceptions < PublicExceptions | |
def call(env) | |
request = ActionDispatch::Request.new(env) | |
status = request.path_info[1..].to_i | |
exception = env['action_dispatch.exception'] | |
message = returned_message(exception, status) | |
attribute = exception.try(:param) || :base | |
code = convert_to_code(status) | |
body = { errors: [ErrorsMapper.single(status: status, attribute: attribute, code: code, message: message)] } | |
render(status, request.formats.first, body) | |
end | |
private | |
def returned_message(exception, status) | |
if status == 500 | |
I18n.t('errors.internal_error.message') | |
else | |
exception.try(:reason) | |
end | |
end | |
def convert_to_code(status) | |
Rack::Utils::HTTP_STATUS_CODES.fetch(status, Rack::Utils::HTTP_STATUS_CODES[500]).downcase | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment