springboot自定义异常处理拦截器

/**
 * 返回自定义的错误页面
 * @author Paracosm
 * @ControllerAdvice 拦截所有的标注有controller这个注解的控制器,
 * @ExceptionHandler 标识这个方法可以做异常处理的 Exception.class表示只要是exception级别的都可以
 */
@ControllerAdvice
@Slf4j
public class ControllerExceptionHandler {

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

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request,Exception e) throws Exception {
        /*记录*/
        log.error("Request URL : {}, Exception : {}", request.getRequestURI(),e.getMessage());


        /*通过注解工具找一个注解有没有存在,如果指定了状态就不应该拦截它 */
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
            throw e;
        }


        /*记录之后希望返回的错误页面*/
        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURI());
        /*获取异常信息*/
        mv.addObject("exception",e);
        mv.setViewName("error/error");
        return mv;
    }

}

自定义异常类


/**
 * @Author Paracosm
 * @Date 2020/12/30 20:29
 * @Version 1.0
 */

/*要继承runtimeexception才能捕获
* 如果要跳转到404页面还需要指定一个返回的状态码 @ResponseStatus(HttpStatus.NOT_FOUND)
* */

@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException{

    public NotFoundException() {
    }

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

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

测试

@GetMapping("/")
    public String index(){
        /*int i = 9/0;*/ // error
        String blog = null;
        if (blog == null) {
            throw new NotFoundException("博客不存在"); //404
        }
        return "index";
    }
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值