【问题标题】:Always response even exception occurs in doorkeeper即使门卫发生异常也始终响应
【发布时间】:2014-01-16 09:28:38
【问题描述】:

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

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

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

【问题讨论】:

    标签: ruby-on-rails api oauth-2.0 doorkeeper


    【解决方案1】:

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

    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
    

    希望这会有所帮助。

    【讨论】:

    猜你喜欢
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    相关资源
    最近更新 更多