Where and how to handle rail exceptions?

I am currently involved in the development of a large rails application that interacts with another product through its own API. This led to a very strange problem of catching errors. For example, when we interact with another product, it may return the authentication error that we expect. Then we catch this error in our API graph and throw an exception, which is then caught and passed to the user in the view.

I do not like this error detection method for several reasons:

  • It does not look like we should expect exceptions and use them in our logic. For example, sometimes we want to overwrite an object, so we catch the exception "the object already exists" and continue and save our model anyway.
  • This requires many special errors. There are several areas in the code where we have if-elses, checking for specific errors and redirecting accordingly.

However, should I use the API to create simpler functions that do not throw exceptions? Is an

if user.has_permission_in_product? if object.doesnt_exist_in_product? do something else redirect somewhere with errors end else redirect somewhere else with errors end 

preferable

 begin do something rescue APIError => e if e.message =~ "no permission" redirect somewhere with errors elsif e.message =~ "already exists" redirect somewhere else with errors end end 

Also, if the former is preferable, how do we deal with actual API errors that can be thrown into these functions? Did we release them in rescue_from in the controller?

Is it better to catch and handle exceptions in the model or throw them into the model and handle them in the controller?

+4
source share
1 answer

Are you looking for rescue_from ?

In your controller, do the following:

 class MyController < ApplicationController rescue_from ActiveRecord::RecordNotFound, :with => :render_missing def render_missing render 'This is a 404', :status => 404 end end 

This will execute the render_missing method every time an ActiveRecord::RecordNotFound exception is ActiveRecord::RecordNotFound .
You can use it with any class of exceptions. And you no longer need to start / save in controllers.

Of course, any exception raised in the model can also be caught by rescue_from.

+12
source

Source: https://habr.com/ru/post/1314343/


All Articles