The Rails controller has a class method called rescue_from method You can specify how to handle exceptions that occur within an action. The following is 500Error (supplementing the error on the WEB server)
application_controller.rb
#If StandardError occurs, process with rescue500
rescue_from StandardError, with: :rescue500
This rescue500 method actually does the processing An argument is specified in the method and an Exception object is included in it.
After render, the path of the ERB template is specified. The render status option is the status code of the HTTP method.
application_controller.rb
private
#Specify the argument e. Contains an error object
def rescue500(e)
render "errors/server_error", status: 500
end
end
To summarize the above
application_controller.rb
class ApplicationController < ActionController::Base
rescue_from StandartError, with: :rescue500
private
def rescue500(e)
render "errors/internal_server_error", status: 500
end
end
It looks like this. Catch an error-> let the action handle it-> display the screen That's the flow.
Since 500 error is not enough, add 400 error. Add code that catches ActiveRecord :: RecordNotFound errors
application_controller.rb
class ApplicationController < ActionController::Base
rescue_from StandartError, with: :rescue500
rescue_from ActiveRecord::RecordNotFound, with: :rescue404
private
def rescue400(e)
render "errors/not_found", status: 404
end
def rescue500(e)
render "errors/internal_server_error", status: 500
end
end
I was able to branch the process due to an error like this.
Since the rescue_from method is for catching exceptions raised by actions Errors that occur during the routing process cannot be captured.
So it is necessary to devise ActionController :: RoutingError, but I think that I will call it again next time.
That's all for today. Thank you very much.
** 81 days to become a full-fledged engineer **
Recommended Posts