Recently Rails introduced a new way of handling errors which removes the need of using begin..end
and makes handling of multiple errors much more easier to read and write.
Read more about ErrorReporting API from here
For using error reporter we need an error subscriber.
What is a subscriber?
A Subscriber is any object with a report
method defined in it. Let’s have a look -
The above code subscribes to our custom ErrorSubscriber
class which reports errors coming from our ErrorService
.
Before
Prior to the addition of error handler in Rails we used begin...end
block and rescue any errors being reported which were logged in the Rails console.
Rescue with multiple exceptions -
After
After the change introduced in this PR, it is now possible to replace the above syntax with the handle
method.
If the block does not raise any Exception/Error then result of the block will be returned or else it returns nil.
We can override this by providing fallback which returns the fallback
value if any error is raised instead of returning nil -
Read about more options supported by ErrorHandler handle
method from here