How to check whether the result comes from an unhandled exception?
The functionality described on this page is available from v0.20.
The Result#from_unhandled_exception? and Result#exception methods answer this question.
Consider the following regular service.
class Service
include ConvenientService::Standard::Config
include ConvenientService::FaultTolerance::Config
def result
success
end
end
It uses the FaultTolerance configuration to automatically rescue all unhandled exceptions and convert them to error results.
In this example, it just returns a success.
result = Service.result
# => <Service::Result status: :success>
So when we query whether the result is from an unhandled exception or not it gives us false.
result.from_unhandled_exception?
# => false
And result.unhandled_exception returns nil respectively.
result.unhandled_exception
# => nil
Let's have a look at other service.
class OtherService
include ConvenientService::Standard::Config
include ConvenientService::FaultTolerance::Config
def result
16 / 0
success
end
end
It intentionally divides 16 by 0 to cause an unhandled exception.
When we invoke the OtherService result, that exception is automatically rescued by the FaultTolerance configuration and converted into error.
result = OtherService.result
# => <OtherService::Result status: :error data_keys: [:exception] message: "ZeroDivisionError...">
Now from_unhandled_exception returns true.
result.from_unhandled_exception?
# => true
And result.unhandled_exception gives access to the original Ruby exception.
result.unhandled_exception
# => #<ZeroDivisionError: divided by 0>
The FaultTolerance configuration rescues only StandardError descendants, not direct Exception descendants, since they are reserved by Ruby.