I was reading this article Exception Handling in Spring MVC, and I don't understand why class extending ExceptionHandlerExceptionResolver
doesn't have any annotations to it.
It should be a bean, right? So it must be annotated with @Component
(or maybe @Service
, but I'm not sure if it belongs to a service layer) annotation or something?
So why it does not have any annotations and how then Spring knows that it's a bean and that it should be used?
@ControllerAdvice is a specialization of the @Component annotation which allows to handle exceptions across the whole application in one global handling component. It can be viewed as an interceptor of exceptions thrown by methods annotated with @RequestMapping and similar.
The Global Exception Handler is a type of workflow designed to determine the project's behavior when encountering an execution error. Only one Global Exception Handler can be set per automation project.
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.
In Java, exception handling is done by try, catch blocks but spring boot also allows us to provide customized global exception handling where we need not to add try catch block everwhere, we can create a separate class for handling exceptions and it also separates the exception handling code from businesss logic code.
You have to manually add your handler to the list of handlers (in the example below I use a SImpleMappingExceptionsResolver, but you can use your own implementation):
package eu.anastasis.readingtrainer.configuration;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
@Configuration
@EnableWebMvc
public class ConfigurationAdapter extends WebMvcConfigurerAdapter {
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
exceptionResolvers.add(new SimpleMappingExceptionResolver());
}
}
Please note that in this way you override any @ControllerAdvice + @ExceptionHandler you may have set (I don't know how to combine both strategies).
Just as an update to @Andrea Pegoretti answer, in Spring 5.X.X WebMvcConfigurerAdapter is deprecated, instead use WebMvcConfigurer interface; please refer to this link for more details.
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