0

我想在 Rails 3 中处理我自己的异常。在 Rails 3 中处理自定义异常和路由错误的最佳流程是什么?

4

1 回答 1

0

您可以按如下方式处理自定义异常:在应用程序控制器中,添加以下内容:

rescue_from Exception, :with => :handle_exception

  def not_found
    render :template => "shared/not_found", :status => 404
  end

  private
  def handle_exception(exception)
    case exception
    when CanCan::AccessDenied
      authenticate_user!
    when ActiveRecord::RecordNotFound
      not_found
    else
      internal_server_error(exception)
    end
  end

  def internal_server_error(exception)
    render :template => "shared/internal_server_error", :status => 500
  end

现在在您的方法中,您可以将错误或异常引发为:

def method_name
  # raise exception_name, "message on exception"
  raise ArgumentError, "missing some param"
end

您还可以通过添加路由来捕获路由错误,如下所示:

match "*any", :to => "application#not_found"

注意:您应该在您的 route.rb 中添加上述路线

于 2013-07-15T10:47:14.473 回答