@RestControllerAdvice注解 @ExceptionHandler注解
RestControllerAdvice+ExceptionHandler这两个注解的组合,被用作项目的全局异常处理。一旦项目中发生了异常,就会进入使用了RestControllerAdvice注解类中使用了ExceptionHandler注解的方法。
下面是一些项目全局异常的处理
@ControllerAdvice(annotations = {RestController.class, Controller.class} ) @ResponseBody @Slf4j public class GlobalExceptionHandler { @ExceptionHandler(SQLIntegrityConstraintViolationException.class) public R<String> excptionHandler(SQLIntegrityConstraintViolationException e){ log.error(e.getMessage()); String message = e.getMessage(); String[] s = message.split(" "); if (message.contains("Duplicate")){ return R.error(s[2]+"already exists"); } return R.error("false"); } @ExceptionHandler(CustomException.class) public R<String> excptionHandler(CustomException e){ log.error(e.getMessage()); return R.error(e.getMessage()); } }
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public RespBean ExceptionHandler(Exception e) { if (e instanceof GlobalException) { GlobalException exception = (GlobalException) e; return RespBean.error(exception.getRespBeanEnum()); } else if (e instanceof BindException) { BindException bindException = (BindException) e; RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR); respBean.setMessage("参数校验异常:" + bindException.getBindingResult().getAllErrors().get(0).getDefaultMessage()); return respBean; } System.out.println("异常信息" + e); return RespBean.error(RespBeanEnum.ERROR); } }
本文作者:xiaoovo
本文链接:https://www.cnblogs.com/xiaoovo/p/17323257.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步