I have a general rails question for which I didn't not find an answer despite good amount of searching around. What is the recommended approach to handling exceptions arising at runtime (unexpected errors) for json rest apis? I am having some trouble using respond_with on update actions. I am having to fallback to respond_to. For example, is this a good pattern? Is there a better alternative? Also, what is the approach other applications take to blanket ALL actions so responses are sent back to the client in the right format (html for html requests and json for application/json requests)?
def update
begin
User.update_attributes(params[:user]))
#assume some other logic here raises an exception (a runtime unexpected error)
rescue => ex
errors = {}
errors['errors'] = [] << ex.message
#not having this rescue here will cause rails to respond with a html error page
#which is not what the client is looking for (client expects json responses)
#however, if I rescue any runtime errors, I have a chance to respond
#in the way the client expects. Also, respond_with here won't work
#because I am getting a 204 response back. So I am forced to use respond_to in the ugly way
respond_to do |format|
format.html # some.html.erb
format.json { render :json => errors.to_json, :status=>400 }
end
end
end
try this