Skip to content

Instantly share code, notes, and snippets.

@coorasse
Created October 20, 2020 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coorasse/c4b54d201218ab2b6f42ec985490b2d1 to your computer and use it in GitHub Desktop.
Save coorasse/c4b54d201218ab2b6f42ec985490b2d1 to your computer and use it in GitHub Desktop.
A Rack Middleware to catch errors in Rails API
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