I am having a normal HTML frontend and a JSON API in my Rails App. Now, if someone calls /api/not_existent_method.json it returns the default HTML 404 page. Is there any way to change this to something like {"error": "not_found"} while leaving the original 404 page for the HTML frontend intact?
I am having a normal HTML frontend and a JSON API in my Rails
Share
A friend pointed me towards a elegant solution that does not only handle 404 but also 500 errors. In fact, it handles every error. The key is, that every error generates an exception that propagates upwards through the stack of rack middlewares until it is handled by one of them. If you are interested in learning more, you can watch this excellent screencast. Rails has it own handlers for exceptions, but you can override them by the less documented
exceptions_appconfig option. Now, you can write your own middleware or you can route the error back into rails, like this:Then you just have to match these routes in your
config/routes.rb:And then you just create a controller for handling this.
One last thing to add: In the development environment, rails usally does not render the 404 or 500 pages but prints a backtrace instead. If you want to see your
ErrorsControllerin action in development mode, then disable the backtrace stuff in yourconfig/enviroments/development.rbfile.