Custom Error Handling In Rails
Contents |
and rescuing custom errors in a Rails application. It's often useful to map custom rails error handling best practices Ruby errors to HTTP response status codes and have Rails render rails api error handling the appropriate HTML error pages. For example, you might have a controller that is acting as a rails ajax error handling simple proxy to a third party service such as Twitter or Facebook, and you need any of the HTTP errors encountered when calling those sites to be
Ruby On Rails Error Handling
handled natively by your app. Another use case would be in a Service-oriented architecture (SOA), where you want any errors in your back end services propagated to your front end web application. In this post we'll demonstrate rescuing status errors in an imaginary proxy controller using the awesome Faraday gem. For the sake of rails controller error handling brevity we've omitted the inclusion of tests though in the wild we'd build such a feature using TDD and our favourite test weapon, RSpec. Not Found To start, let's handle basic 404 Not Found errors that occur when calling a service. For this we'll need a custom error class that extends StandardError. # lib/errors/not_found.rb module Errors class NotFound < StandardError; end end Faraday provides a neat Rack-esque middleware feature. By creating our own custom middleware we can catch any Faraday 404s and raise our custom error. Furthermore, we can re-use the middleware anytime we need the same behaviour. # lib/errors/raise_error.rb module Errors class RaiseError < Faraday::Response::Middleware def on_complete(env) raise Errors::NotFound if env[:status] == 404 end end end Now for the proxy controller. # app/controllers/proxy_controller.rb class ProxyController < ApplicationController def index connection = Faraday.new(:url => 'http://someservice') do |f| f.adapter Faraday.default_adapter f.use Errors::RaiseError # Include custom middleware end response = connection.get('/some/resource') render :text => response.body end end At this point any NotFounds raised wi
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this rails .find error handling site About Us Learn more about Stack Overflow the company Business Learn more
Rails Custom Error Pages
about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x
Custom Error Handling In Asp.net Mvc 4
Dismiss Join the Stack Overflow Community Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up Raise custom https://wearestac.com/blog/raising-and-rescuing-custom-errors-in-rails Exception with arguments up vote 19 down vote favorite 8 I'm defining a custom Exception on a model in rails as kind of a wrapper Exception: (begin[code]rescue[raise custom exception]end) When I raise the Exception, I'd like to pass it some info about a) the instance of the model whose internal functions raise the error, and b) the error that was caught. This is going on http://stackoverflow.com/questions/11636874/raise-custom-exception-with-arguments an automated import method of a model that gets populated by POST request to from foreign datasource. tldr; How can one pass arguments to an Exception, given that you define the Exception yourself? I have an initialize method on that Exception but the raise syntax seems to only accept an Exception class and message, no optional parameters that get passed into the instantiation process. ruby-on-rails ruby exception exception-handling share|improve this question asked Jul 24 '12 at 18:15 Chris Keele 1,51611646 add a comment| 4 Answers 4 active oldest votes up vote 35 down vote accepted create an instance of your exception with new: class CustomException < StandardError def initialize(data) @data = data end end # => nil raise CustomException.new(bla: "blupp") # CustomException: CustomException share|improve this answer edited May 22 '14 at 12:58 answered Jul 24 '12 at 18:25 phoet 15.4k32853 15 I've been using this for a year now, and thought I'd add: now every time I want to do this and forget how, I take a peek at cancan's exceptions to remind myself. The last error follows very good form for more complicated exceptions. –Chris Keele Mar 31
error can (and should) be handled correctly in your application. Let me give you an example of how to handle a ActiveRecord::RecordNotFound exception. Let’s https://ariejan.net/2011/10/14/rails-3-customized-exception-handling/ assume you have an application that could show a user profile: # GET /p/:name def show @profile = Profile.find(params[:name]) end Now, it may happen that the :name paramater contains a value that cannot be found in our database, most likely because someone made a typo in the URL. If Profile#find cannot get a proper result it will throw error handling ActiveRecord::RecordNotFound. Now, instead of showing the user the (by default ugly) 404 page from public/404.html we want to do something more fancy. Action-specific exception handling Here’s one solution: # GET /p/:name def show @profile = Profile.find(params[:name]) rescue render :template => 'application/profile_not_found', :status => :not_found end You can now create app/views/applicaiton/profile_not_found.html.haml and give a nice custom error message to your custom error handling user. You may try to find some matching profiles to :name or show a search box. Global exception handling The above example only works for the specific profile show action. It’s also possible to hanlde exceptions on the application level. Your show action still looks like this: # GET /p/:name def show @profile = Profile.find(params[:name]) end Then, in your app/controllers/application_controller.rb add this: class ApplicationController < ActionController::Base rescue_from ActiveRecord::RecordNotFound, :with => :rescue_not_found protected def rescue_not_found render :template => 'application/not_found', :status => :not_found end end Whenever an ActiveRecord::RecordNotFound exception is thrown (and not handled by the action itself), it will be handled by your ApplicationController. Custom exceptions It’s possible to throw your own custom exceptions and handle them in different ways. Like this: # Define your own error class MyApp::ProfileNotFoundError < StandardError end # GET /p/:name def show @profile = Profile.find_by_name(params[:name]) raise MyApp::ProfileNotFoundError if @profile.nil? end And add this to your ApplicationController: rescue_from MyApp::ProfileNotFoundError, :with => :profile_not_found Optionally, if you don’t want to write that custom profile_not_found method, you may also supply a block: rescue_from MyApp::ProfileNotFoundError