What is good practice for error handling for the Rails API

I'm working on this site, where using Ruby on Rails as APIs for this purpose, what are the good back end error handling techniques? For example, if the answer is "not found", how can I json

reliably return data indicating such messages?

EDIT:

Adding an example and additional information for clarification

For example in the backend if I have

def top_photos
  user = User.find params[:user_id]
  photos = user.photos.order(created_at: :desc)
                             .limit(10)
  render json: user, status: 200
end

      

if there are any errors in the process such as the user with the data user_id

cannot be found, what is a good practice to return the json formatted data to the front end so that the error can be handled in the frontend?

A little more background: the website already has 50 controllers, what can I do to keep the changes minimal and responsive?

+3


source to share


1 answer


Assuming your code states the following, the status can be displayed in each

user = {
  name: "Tang",
  id: 40
}
render :json => user.to_json, :status => :ok

      

Popular Status Codes, HTTP Status Codes and RESTful APIs:

200 :ok
201 :created
202 :accepted
400 :bad_request
401 :unauthorized
403 :forbidden
500 :internal_server_error

      




To eliminate common mistakes

If you have your own route for your apis, you can put it in your "ApplicationController" (or the main controller of your namespace, usually ApiController):

 # CUSTOM EXCEPTION HANDLING
  rescue_from StandardError do |e|
    error(e)
  end

  def routing_error
    raise ActionController::RoutingError.new(params[:path])
  end

  protected

  def error(e)
    #render :template => "#{Rails::root}/public/404.html"
    if env["ORIGINAL_FULLPATH"] =~ /^\/api/
    error_info = {
      :error => "internal-server-error",
      :exception => "#{e.class.name} : #{e.message}",
    }
    error_info[:trace] = e.backtrace[0,10] if Rails.env.development?
    render :json => error_info.to_json, :status => 500
    else
      #render :text => "500 Internal Server Error", :status => 500 # You can render your own template here
      raise e
    end
  end

      

+9


source







All Articles