Reputation: 14286
In case and exception is thrown while Guice is creating a class a
ProvisionException
wraps the original exception.
Is there a way to force the throw of the original exception instead?
For instance:
@Inject
public myClass() {
throw new MySpecificException();
}
I know, I can catch ProvisionException
and call getCause()
to unwrap and get to the MySpecificException
. However, if possible I would prefer to override the default Guice exception instead.
Upvotes: 1
Views: 1130
Reputation: 32323
ProvisionException
does a lot more than wrap one Exception; Guice is set up to catch many exceptions at once, roll them together into a single Exception and send a convenient, useful message back to you to figure out what went wrong.
For example, in the Guice source code there's lots of code like this:
try {
result = callable.call();
// Make sure we don't return the provisioned object if there were any errors
// injecting its field/method dependencies.
errors.throwIfNewErrors(numErrorsBefore);
} catch(ErrorsException ee) {
exceptionDuringProvision = ee;
throw new ProvisionException(errors.merge(ee.getErrors()).getMessages())
}
The error handling system is so deeply integrated that you're not going to be able to extract it out; and, honestly, why would you want to? The whole point of doing it this way is to make it easy for you to isolate the problem. If you're getting a ProvisionException
, that means that your code is doing the wrong thing and needs to be changed; it is not the sort of thing that you can recover from and return to normal operations.
In my production system, I catch many exceptions in various places and handle them, log them and attempt to recover. But, ProvisionException
is not one of them; if my system throws it, I want the whole darn thing to crash so I can figure it out immediately and fix it. (Of course, by the time I'm deploying a new build, it's been thoroughly tested so that I know, at the very least, if there is a problem it's not going to be ProvisionException
).
Upvotes: 2