zoukankan      html  css  js  c++  java
  • 用@ExceptionHandler 来进行异常处理

    有时候我们想统一处理一个Controller中抛出的异常怎么搞呢?

    直接在Controller里面加上用@ExceptionHandler标注一个处理异常的方法像下面这样子

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void processMethod(MissingServletRequestParameterException ex,HttpServletRequest request ,HttpServletResponse response) throws IOException {
        System.out.println("抛异常了!"+ex.getLocalizedMessage());
        logger.error("抛异常了!"+ex.getLocalizedMessage());
        response.getWriter().printf(ex.getMessage());
        response.flushBuffer();
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    这样,Controller里面的方法抛出了MissingServletRequestParameterException异常就会执行上面的这个方法来进行异常处理。 
    像我下面的代码

    @RequestMapping("/index")
    public String index(@MyUser User user,@RequestParam String id,ModelMap modelMap){
        return "login";
    }
    • 1
    • 2
    • 3
    • 4
    • 1
    • 2
    • 3
    • 4

    如果我没有传入id值,那么就会抛出MissingServletRequestParameterException的异常,就会被上面的异常处理方法处理。

    上面的@ExceptionHandler(MissingServletRequestParameterException.class)这个注解的value的值是一个Class[]类型的,这里的ExceptionClass是你自己指定的,你也可以指定多个需要处理的异常类型,比如这样@ExceptionHandler(value = {MissingServletRequestParameterException.class,BindException.class}),这样就会处理多个异常了。

    但这个只会是在当前的Controller里面起作用,如果想在所有的Controller里面统一处理异常的话,可以用@ControllerAdvice来创建一个专门处理的类。

  • 相关阅读:
    手机端html滑动处理
    css控制div上下移动
    倒计时javascript
    PHP解决抢购等阻塞式高并发redis处理思路
    jQuery判断当前元素是第几个元素
    CSS 实现盒子水平居中、垂直居中和水平垂直居中的方法
    yii1.* session无法调用问题
    百度小程序坑坑坑
    php等比缩放图片
    lavarel的小失误
  • 原文地址:https://www.cnblogs.com/exmyth/p/7236872.html
Copyright © 2011-2022 走看看