How to handle exception in springboot

SpringBoot exception handling in five ways: a, a custom error page:

SpringBoot default exception handling mechanism need to be in SRC/main/resources/templates directory to create the error. The HTML page (no matter what exceptions will intercept). Different to intercept errors is necessary under the templates to create the error folder named with error code to the HTML

2: @ ControllerAdvice + @ ExceptionHandler annotation processing abnormal
you need to create a global exception class that can handle the exception. You need to add the @ControllerAdvice annotation on this class.
@ ControllerAdvice
public class GlobalException {
@ ExceptionHandler (value = {Java. Lang. ArithmeticException. Class})
public ModelAndView arithmeticExceptionHandler (Exception e) {
ModelAndView mv = new ModelAndView();
mv. AddObject (” error “, e. oString ());
mv. SetViewName (” error “);
return mv;
}
}

> All you need to do is add the following method to the controller:
@ExceptionHandler(value={java.lang.ArithmeticException.class})
public ModelAndView arithmeticExceptionHandler(Exception e) {
ModelAndView mv = new ModelAndView();
mv. AddObject (” error “, e. oString ());
mv. SetViewName (” error “);
return mv;
}

requires the implementation of the HandlerExceptionResolver interface in the global exception class
@Configuration
public class GlobalException implements HandlerExceptionResolver {
@Override
public ModelAndView resolverException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) {
ModelAndView mv = new ModelAndView();
if(Exception instanceof ArithMeticException) {
.setViewName (” error “);
}
mv. AddObject (” error “, the exception. The toString ());
return mv;

}}
5, configuration, exception handling SimpleMappingExceptionResolver
in the global exception class to add a method to complete the unification of the exception class
@Configuration
public class GlobalException {
public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
Properties properties = new Properties();
properties. The put (” Java. Lang. ArithmeticException “, “error”);
resolver.setExceptionMappings(properties);
return resolver;
}
}

Read More: