JAVA入门[17]-ControllerAdvice处理exception

本文介绍了如何使用@ControllerAdvice实现Spring MVC中的全局异常处理。通过自定义异常类和GlobalExceptionHandler类,可以针对不同类型的异常返回特定的视图页面。
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值