谷粒商城品牌管理(九)
61-64可以查看下面2篇博客
https://www.cnblogs.com/dalianpai/p/12984290.html
https://www.cnblogs.com/dalianpai/p/12984850.html
65-66 JSR303校验和统一异常处理
JSR303得到了很好的学习的机会,统一异常处理的码值是通过枚举来实现的,也有一定的可取之处。
在common项目下引入jar包
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.1.2.Final</version> </dependency>
Bo类
注意:当时截图的时候忘记把BindingResult删了,有这个会导致异常捕获不到。
统一异常处理
/** * @author WGR * @create 2020/6/1 -- 19:49 */ @Slf4j @RestControllerAdvice("com.dalianpai.gulimall.product.controller") public class GulimallExceptionControllerAdvice { @ExceptionHandler(value = MethodArgumentNotValidException.class) public R handleVaildException(MethodArgumentNotValidException e){ log.info("数据校验出现问题{},异常类型:{}",e.getMessage(),e.getClass()); BindingResult bindingResult = e.getBindingResult(); Map<String, String> map = new HashMap<>(); bindingResult.getFieldErrors().forEach((fieldError) ->{ map.put(fieldError.getField(),fieldError.getDefaultMessage()); } ); return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMessage()).put("data",map); } @ExceptionHandler(value = Throwable.class) public R handleException(Throwable throwable){ log.error("错误:",throwable); return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMessage()); } }
枚举类:
/** * @author WGR * @create 2020/6/1 -- 20:10 */ public enum BizCodeEnume { UNKNOW_EXCEPTION(10000,"系统未知异常"), VAILD_EXCEPTION(10001,"参数格式校验失败"); private int code; private String message; BizCodeEnume(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public String getMessage() { return message; } }