[JAVA] Spring Boot project development on exception class handling

Posted by hrichman on Thu, 06 Jan 2022 19:32:01 +0100

1. Preface

Exceptions refer to abnormal phenomena that occur during the running of a program, such as user input errors, division by zero, non-existent files to be processed, array subscripts crossing bounds, and so on.

2. Classification of Exceptions

There are many exception classes defined in the JDK that correspond to a variety of possible exception events, all of which are an instance derived from the Throwable class. If the built-in exception classes are not sufficient, you can also create your own.
Java classifies exceptions. Different types of exceptions are represented by different Java classes. The root class of all exceptions is java.lang.Throwable, two subclasses are derived under Throwable: Error and Exception. We usually use Exception (which is also my main contact right now).
Of course, we can also customize the exception class so that it inherits Exception.

3. Handling Exceptions in Spring Boot Project Development

There are many ways to handle exceptions during project development. Here's how to handle exceptions using the @ExceptionHandler annotation in SpringMVC.
A method can be specified as an exception handling method using the annotation @ExceptionHandler. The comment has only one optional attribute value, a Class<?> Array that specifies the exception class to be handled by the annotated method, that is, the exception to be matched.
The annotated methods can return ModelAndView, String, or void with arbitrary method names, and method parameters can be Exception and its subclass objects, HttpServletRequest, HttpServletResponse, and so on. The system automatically assigns values to these method parameters.

1. First define a custom exception class and set its HTTP response status code to NOT_FOUND and overrides three important methods of its parent class.

//Set the custom exception class status code to NOT_FOUND
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {

    public NotFoundException() {
        super();
    }

    public NotFoundException(String message) {
        super(message);
    }

    public NotFoundException(String message, Throwable cause) {
        super(message, cause);
    }
}

2. Define exception handling classes
The @ControllerAdvice note is used here: literally, Controller Enhancement, which enhances the functionality of the Controller object. @ExceptionHandler can be used in classes decorated with @ControllerAdvice. The goal is to focus exception handling methods on one class.

@ControllerAdvice
public class ControllerException {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request,Exception e) throws Exception {
    
    	//Print out log to page source code
        logger.error("Request URL : {},Exception : {}",request.getRequestURL(),e);

		//Determine if the status code is empty
        if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
            throw e;
        }
        
        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURL());
        mv.addObject("exception",e);
        mv.setViewName("error/error.html");
        return mv;
    }

}

When the following program throws an exception, if the exception type is NotFoundException, it is left to Spring Boot to resolve itself. Spring Boot will find the corresponding page based on the status code (which can be customized under the thymeleaf folder) and return. Others will jump to the error page

@Controller
public class indexController {

    @GetMapping("/")
    public String index(){
//        int a = 9 / 0;
        String blog = null;
        if(blog == null){
            throw new NotFoundException("Blog does not exist");
        }
        return "index";
    }

}

Topics: Java Spring Spring Boot Back-end