1

Two-part Rails question:

Part 1

When a Rails controller raises an unhandled exception, an HTTP 500 (Internal Server Error) status code is typically returned in the response to the caller.

However, I've observed that certain specific types of exceptions cause a different HTTP status code to be returned. For example, an unhandled ActiveRecord::RecordNotFound exception (as from a find_by! call that failed to find a matching record) causes an HTTP 404 Not Found, rather than an HTTP 500, to be returned.

Short of actually trying it, how can I know which HTTP status code Rails controllers will return for a particular class of unhandled exception?

Part 2

If I want to customize which HTTP status code controllers return for a particular class of exception -- say, a custom derived class of StandardError defined in my application -- how can that be done?

1 Answer 1

1

The default mapping of exception classes to HTTP response codes for Rails controllers is in config.action_dispatch.rescue_responses, shown here: https://guides.rubyonrails.org/configuring.html#config-action-dispatch-rescue-responses

This default behavior can be altered or extended by assigning a value to that config.action_dispatch.rescue_responses hash (e.g. in config/application.rb). For example:

config.action_dispatch.rescue_responses['MyCustomError'] = :unprocessable_entity
Sign up to request clarification or add additional context in comments.

2 Comments

If you want to go beyond this and customize the entire handling of errors you can use config.exceptions_app which is the Rack application called by Rails when it handles an uncaught exception.
You can also manage the status code returned for each exception per controller with: apidock.com/rails/ActiveSupport/Rescuable/ClassMethods/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.