My team is using a hypermedia API built on top of collection+JSON using our modified collection+JSON gem. We would prefer to see this when there is an error and the request format is JSON:
{
collection:
{
error:
{
'title': 'Application Error',
'message': 'Sorry, we can't process your request at this time',
'code': 500
}
}
}
instead of this, which can be hard for JSON parsers to handle:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Action Controller: Exception caught</title>
<style>
body {
background-color: #FAFAFA;
color: #333;
margin: 0px;
}
I know how to do that using Rails' rescue_from
in the ApplicationController:
class ApplicationController < ActionController::Base
rescue_from ActionController::UnpermittedParameters, with: :bad_parameters
rescue_from Exception, with: :exception_handling
def bad_parameters
respond_to do |format|
format.html do
if( request_is_local )
# render helpful stack trace and stuff
else
render :file => 'public/404.html', :status => :not_found, :layout => false
end
end
format.json { render :json => BadParametersEndpoint.new(:context => self).to_json, :status => :not_found }
end
end
def exception_handling(exception)
respond_to do |format|
format.xml { render :xml => '<xml><error>Whatever</error></xml>', :status => 500 }
format.json { render :json => ExceptionEndpoint.new(:exception => exception), :status => 500 }
format.html do
if( Rails.env == 'development' ) # there must be a better test ...
# somehow using config.consider_all_requests_local
# render helpful stack trace and stuff
else
render :file => 'public/500.html', :status => 500, :layout => false
end
end
end
end
end
But if I do that, how do I keep the handy HTML view provided by Rails or, better yet, the one provided by a gem like better_errors?