Unified exception handling_study notes

SpringMVC provides @ControllerAdvicefunctions

  1. Extract an exception handling class, add @ControllerAdviceannotations to the class , and basePackagesspecify through attributes that it should handle the exceptions thrown by those classes;
@ControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
    
    
    
}
  1. Write a method to handle exceptions, and add @ExceptionHandlerannotations 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());
    }
}

Guess you like

Origin blog.csdn.net/qq_40084325/article/details/109481064