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 @   王叫兽  阅读(329)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示