Always response even exception occurs in doorkeeper

696 Views Asked by At

I'm using Doorkeeper with rails-api to implement oAuth2 with password workflow:

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

Right now when exception occurs it displays 500 template html response from rails. What I want to do is rescue any unexpected exception, then I want to custom the response error message base on exception that occurred in json response.

1

There are 1 best solutions below

1
On

as the classes defined within the doorkeeper API will extend the Application controller, we can define the following in the Application controller

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

Then you can define the errors specifically in the 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

Hope this helps.