JSR 303参数校验 统一异常处理 优化业务代码 (二)
1 全局异常处理
1 参数校验的地方 在Controller 每次都要写一大块代码 太麻烦了
2 优化:用 ControllerAdvice 来捕获 参数校验时 出现的异常信息
增加 GulimallExceptionControllerAdvice 来捕获异常
package com.atguigu.gulimall.product.exception; import com.atguigu.common.utils.R; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.bind.BindResult; import org.springframework.validation.BindingResult; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.HashMap; import java.util.Map; /** * 集中处理所有异常 */ @Slf4j @RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller") public class GulimallExceptionControllerAdvice { @ExceptionHandler(value = MethodArgumentNotValidException.class) //指定能处理什么异常 public R handleVaildException(MethodArgumentNotValidException e){ BindingResult result= e.getBindingResult(); Map<String,String> errorMap=new HashMap<>(); result.getFieldErrors().forEach(fieldError->{ errorMap.put(fieldError.getField(),fieldError.getDefaultMessage()); }); log.error("数据校验出现问题{},异常类型:{}",e.getMessage(),e.getClass()); return R.error(400,"数据校验出现错误").put("error",errorMap); } }
简化业务代码
3 测试
本文作者:KwFruit
本文链接:https://www.cnblogs.com/mangoubiubiu/p/14426422.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
JSR303
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步