[Architecture] Spring Boot global exception handler using the @ ExceptionHandler + @ ControllerAdvice

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/sinat_27933301/article/details/101949881
annotation DEFINITIONS
ExceptionHandler The method of annotations, acting Controller level, the ExceptionHandler annotation to define an exception handler a Controler
ControllerAdvice Class notes, acting on the entire Spring project, ControllerAdvice annotations define a global exception handler

  Note that, ExceptionHandler a higher priority than ControllerAdvice, namely giving priority to ExceptionHandler labeling method of treatment.

/**
 * 全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(code = HttpStatus.NOT_FOUND)
    public String e404() {
        return "error/404.html";
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public String e500() {
        return "error/500.html";
    }
}
@Controller
public class UserController {

    /**
	 * 局部异常处理
	 */
    @ExceptionHandler(BusinessException.class)
    public String exPage(Exception ex, Model model) {
        model.addAttribute("ex", ex);

        return  "/error/business.html";
    }
}

Spring Boot default resource path, the view class ResourceProperties spring-boot-autoconfigure package.

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{
     "classpath:/META-INF/resources/",
     "classpath:/resources/", 
     "classpath:/static/", 
     "classpath:/public/"};

Guess you like

Origin blog.csdn.net/sinat_27933301/article/details/101949881