首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Rails:捕获rails控制器中的所有异常

Rails:捕获rails控制器中的所有异常
EN

Stack Overflow用户
提问于 2010-09-12 16:01:09
回答 5查看 113.7K关注 0票数 98

有没有办法在rails控制器中捕获所有未捕获的异常,如下所示:

def delete
  schedule_id = params[:scheduleId]
  begin
    Schedules.delete(schedule_id)
  rescue ActiveRecord::RecordNotFound
    render :json => "record not found"
  rescue ActiveRecord::CatchAll
    #Only comes in here if nothing else catches the error
  end
  render :json => "ok"
end

谢谢

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-09-12 16:36:16

begin
  # do something dodgy
rescue ActiveRecord::RecordNotFound
  # handle not found error
rescue ActiveRecord::ActiveRecordError
  # handle other ActiveRecord errors
rescue # StandardError
  # handle most other errors
rescue Exception
  # handle everything else
  raise
end
票数 98
EN

Stack Overflow用户

发布于 2011-07-21 16:09:26

您还可以定义rescue_from方法。

class ApplicationController < ActionController::Base
  rescue_from ActionController::RoutingError, :with => :error_render_method

  def error_render_method
    respond_to do |type|
      type.xml { render :template => "errors/error_404", :status => 404 }
      type.all  { render :nothing => true, :status => 404 }
    end
    true
  end
end

根据您的目标,您可能还希望考虑不在每个控制器的基础上处理异常。相反,可以使用像exception_handler gem这样的工具来一致地管理对异常的响应。此外,此方法还将处理发生在中间件层的异常,如请求解析或应用程序看不到的数据库连接错误。exception_notifier gem可能也会引起人们的兴趣。

票数 207
EN

Stack Overflow用户

发布于 2015-05-18 21:14:13

您可以按类型捕获异常:

rescue_from ::ActiveRecord::RecordNotFound, with: :record_not_found
rescue_from ::NameError, with: :error_occurred
rescue_from ::ActionController::RoutingError, with: :error_occurred
# Don't resuce from Exception as it will resuce from everything as mentioned here "http://stackoverflow.com/questions/10048173/why-is-it-bad-style-to-rescue-exception-e-in-ruby" Thanks for @Thibaut Barrère for mention that
# rescue_from ::Exception, with: :error_occurred 

protected

def record_not_found(exception)
  render json: {error: exception.message}.to_json, status: 404
  return
end

def error_occurred(exception)
  render json: {error: exception.message}.to_json, status: 500
  return
end
票数 39
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3694153

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档