始终响应甚至在门卫中发生异常

时间:2014-01-16 09:28:39

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

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

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

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

1 个答案:

答案 0 :(得分:0)

由于门卫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

希望这有帮助。

相关问题