统一异常处理_学习笔记

SpringMVC提供了@ControllerAdvice功能

  1. 抽取一个异常处理类,在类上添加@ControllerAdvice注解,并且通过basePackages属性指定它要处理那些类抛出的异常;
@ControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
    
    
    
}
  1. 编写处理异常的方法,并且在方法上添加@ExceptionHandler注解,来告诉Springmvc这个方法能处理哪些异常;
    在方法参数中传入响应的异常类型
@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());
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40084325/article/details/109481064