编程语言
首页 > 编程语言> > Java @ControllerAdvice 全局异常处理

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; //自己需要实现的异常处理
    }

}

 

标签:Java,System,getMessage,println,ControllerAdvice,全局,异常,class,out
来源: https://www.cnblogs.com/younger5/p/15845427.html