The @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the client. Define a class that extends the RuntimeException class. You can define the @ExceptionHandler method to handle the exceptions as shown.
@ControllerAdvice is a annotation provided by Spring allowing you to write global code that can be applied to a wide range of controllers, varying from all controllers to a chosen package or even a specific annotation.
Spring MVC provides exception handling for your web application to make sure you are sending your own exception page instead of the server-generated exception to the user. The @ExceptionHandler annotation is used to detect certain runtime exceptions and send responses according to the exception.
The @ExceptionHandler annotation is required to handle the type of exceptions which are thrown and the corresponding method will be able to handle the exceptions.
Let's say I have a method that throws an Exception of some kind. The exception-throwing code lies in a third-party library that access an external service. I have a few classes that do a good deal of work with external services and there is a LOT of exception handling throughout to deal with potential problems. The issue I'm hitting is that I may have a lot of exceptions, but I may only need to perform one of a few actions if there is one, and there are a ton of try/catch blocks peppered about. The type of exception may not even be relevant, or different methods may throw the same type of exception, but different actions need to be taken depending on the method throwing it.
What I'm looking for is an annotation that can supplant try/catch and simply dictate the behavior to be taken when there is an exception in that method. I know that Spring ApsectJ can do this sort of thing, but I'm not currently able to easily add any new dependencies or modify the pom to adjust existing ones. As such, I'm hoping that this can be accomplished with a custom annotation. For example:
@Catcher(action=SomeEnum.SOME_ACTION)
public void doSomething(ServiceObj obj) throws SomeException {
ExternalService.makeThingsHappen(obj);
}
I would presume that a separate class would handle exceptions, of course. An additional difficulty is that I would need the ServiceObj that is passed as well. If makeThingsHappen() fails, I may need obj to perform additional actions. The action variable will tell the handler class what to do with obj.
Can this be done without severe muckery, or am I hoping for something that may not exist?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With