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?
source share