0

我正在使用 Doorkeeper 和 rails-api 来实现 oAuth2 和密码工作流程:

resource_owner_from_credentials do
  FacebookAuthorization.create(params[:username])
end

现在,当发生异常时,它会显示来自 rails 的 500 模板 html 响应。我想做的是挽救任何意外异常,然后我想根据 json 响应中发生的异常自定义响应错误消息。

4

1 回答 1

0

由于门卫 API 中定义的类将扩展应用程序控制器,我们可以在应用程序控制器中定义以下内容

unless Rails.application.config.consider_all_requests_local
   rescue_from Exception, with: :render_500
   rescue_from ActionController::RoutingError, with: :render_404
   rescue_from ActionController::UnknownController, with: :render_404
   rescue_from ActionController::UnknownAction, with: :render_404
   rescue_from ActiveRecord::RecordNotFound, with: :render_404   
end


 private

 #error handling
 def render_404(exception)
   @not_found_path = exception.message
   respond_to do |format|
    format.html { render file: 'public/404.html', status: 404, layout: false }
    format.all { render nothing: true, status: 404 }
   end
 end

 def render_500(exception)
   @error = exception
   respond_to do |format|
     format.html { render file: 'public/500.html', status: 500, layout: false }
     format.all { render nothing: true, status: 500}
   end
 end

然后您可以在 ErrorsController 中专门定义错误

class ErrorsController < ActionController::Base
  def not_found
    if request.url.match('api')
      render :json => {:error => "Not Found"}.to_json, :status => 404
    else
      render file: 'public/404.html', :status => 404, layout: false
    end
  end

  def exception
    if request.url.match('api')
      render :json => {:error => "Internal Server Error"}.to_json, :status => 500
    else
      render file: 'public/500.html', :status => 500, layout: false
    end
  end
end

希望这可以帮助。

于 2014-01-17T06:19:51.697 回答