how to handle exceptions in JSON based RESTful code?

(I found the answer just before I hit [Post your question]. But this might help someone else as well…)

Use ActionController’s rescue_from

The answer is to use ActionController’s rescue_from, as described in this Guide and documented here. In particular, you can replace the default rendering of the default 404.html and 500.html files along these lines:

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

private
  def record_not_found(error)
    render :json => {:error => error.message}, :status => :not_found
  end 
end

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)