SpringMVC provides @ControllerAdvice
functions
- Extract an exception handling class, add
@ControllerAdvice
annotations to the class , andbasePackages
specify through attributes that it should handle the exceptions thrown by those classes;
@ControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
}
- Write a method to handle exceptions, and add
@ExceptionHandler
annotations to the method to tell Springmvc which exceptions this method can handle;
pass in the response exception type in the method parameters
@Slf4j
@ControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
@ResponseBody
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public R handleValidException(MethodArgumentNotValidException e){
log.info("数据校验出现问题:{},异常类型:{}",e.getMessage(),e.getClass());
BindingResult bindingResult = e.getBindingResult();
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
Map<String,String> map = new HashMap<>();
fieldErrors.forEach((fieldError)->{
map.put(fieldError.getField(),fieldError.getDefaultMessage());
});
return R.error(400,"数据校验错误").put("data",map);
}
@ResponseBody
@ExceptionHandler(value = Throwable.class)
public R handleException(Throwable throwable){
return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
}
}