Saturday 15 February 2014

What are the good practice for error handling for Rails API -



What are the good practice for error handling for Rails API -

i'm working on website using ruby on rails end api, such purpose, practices error handling in end? example, if response 'not found', how can homecoming json info indicating such messages robustly?

edit:

adding illustration , more background info clarification

for example, in backend, if 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 errors in process, user given user_id cannot found, a practice homecoming json format info front end end error handled in frontend?

a little more background: there 50+ controllers existing in website, can alter minimal , adaptive?

assuming next code, status can rendered in every

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

popular status codes, check out http status codes , restful api crafting:

200 :ok 201 :created 202 :accepted 400 :bad_request 401 :unauthorized 403 :forbidden 500 :internal_server_error for handling general errors

if have custom route apis may set in "applicationcontroller" (or in main controller of namespace, apicontroller):

# custom exception handling rescue_from exception |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 # can render own template here raise e end end

api ruby-on-rails-4

No comments:

Post a Comment