小言_互联网的博客

【Spring Boot架构】全局异常处理@ExceptionHandler+@ControllerAdvice的使用

389人阅读  评论(0)
注解 释义
ExceptionHandler 方法注解,作用于Controller 级别,ExceptionHandler注解为一个Controler定义一个异常处理器
ControllerAdvice 类注解,作用于 整个Spring 工程,ControllerAdvice注解定义了一个全局的异常处理器

  需要注意的是,ExceptionHandler 的优先级比 ControllerAdvice 高,即优先让 ExceptionHandler 标注的方法处理。

/**
 * 全局异常处理
 */
@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的默认资源路径,可查看spring-boot-autoconfigure包的ResourceProperties类。

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

转载:https://blog.csdn.net/sinat_27933301/article/details/101949881
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场