Java @ControllerAdvice 全局异常处理

@ControllerAdvice,它是一个Controller增强器,可对controller中被 @RequestMapping注解的方法加一些逻辑处理。最常用的就是异常处理

1.编写异常捕捉组件

@ControllerAdvice
public class ExceptionHandle {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity exceptionHandle(HttpServletRequest req,Exception e){
        System.out.println("exceptionHandle handle");
        System.out.println(e.getMessage());
        return null; //自己需要实现的异常处理
    }

    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResponseEntity nullPointExceptionHandle(HttpServletRequest req,Exception e){ // 处理方法参数的异常类型
        System.out.println("nullPointExceptionHandle");
        logger.error("发生业务异常!原因是:{}",e.getMessage());
        System.out.println(e.getMessage());
        return null;//自己需要实现的异常处理
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity runTimeHandle(HttpServletRequest req,RuntimeException e){
        System.out.println("runTimeHandle");
        System.out.println(e.getMessage());
        return null; //自己需要实现的异常处理
    }

}

 

posted @ 2022-01-26 09:22  王叫兽  阅读(325)  评论(0编辑  收藏  举报