JAVA入门[17]-ControllerAdvice处理exception

1.关于@ControllerAdvice

@ControllerAdvice注解本身已经使用了@Component,因此@ControllerAdvice注解所标注的类将会自动被组件扫描获取到,就像带有@Component注解的类一样。另外,在带有@ControllerAdvice注解的类中,异常处理会应用到所有控制器中带有@RequestMapping注解的方法上。

2.使用示例

自定义exception:

@ResponseStatus(value = HttpStatus.NOT_FOUND,reason = "file not found")
public class NotFoundException extends RuntimeException {
}

  

定义ControllerAdvice

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NotFoundException.class)
    public String NotFoundHandler()
    {
        return "error/404.html";
    }

    @ExceptionHandler(Exception.class)
    public String ErrorHandler(){
        return "error/error.html";
    }
}

  

错误页controller

@RequestMapping("/error404")
    public String error(){
        throw new NotFoundException();
    }

    @RequestMapping("/error")
    public String errorNotFound() throws Exception {
        throw new Exception();
    }

  

view:

在views/error目录下新增error.html和404.html

3.测试

http://localhost:8092/category/error404

http://localhost:8092/category/error

4.参考资料推荐

http://viralpatel.net/blogs/spring-mvc-exception-handling-controlleradvice-annotation/

原文地址:https://www.cnblogs.com/janes/p/6933958.html