今天依旧学习了黑马的瑞吉外卖,以下是我跟着视频学习写的代码,关于全局异常处理器:
//拦截类上加载了RestController这个类 @ControllerAdvice(annotations = {RestController.class}) //写方法需要返回JSON数据,最终把数据封装为JSON进行返回 @ResponseBody @Slf4j public class GlobalExceptionHandler { /** * 异常处理方法,关于SQLIntegrityConstraintViolationException数据库异常处理 * @return */ @ExceptionHandler(SQLIntegrityConstraintViolationException.class) public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){ log.error(e.getMessage()); if(e.getMessage().contains("Duplicate entry")){ String[] spilt = e.getMessage().split(" "); String msg = spilt[2] + "已存在"; return R.error(msg); } return R.error("未知错误"); } /** * 异常处理方法,业务逻辑处理 * @return */ @ExceptionHandler(CustomException.class) public R<String> customExceptionHandler(CustomException e){ return R.error(e.getMessage()); } }
欢迎大家一起学习,有不足地方还请指出。