当前位置: 首页 > news >正文

如何使用SpringBoot处理全局异常

如何使用SpringBoot处理全局异常

使用@ControllerAdvice 和 @ExceptionHandler处理全局异常

参考:

@ControllerAdvice
@ResponseBody
@Slf4j
public class ExceptionHandler {@ResponseStatus(HttpStatus.OK)@org.springframework.web.bind.annotation.ExceptionHandler(value = {MissingServletRequestParameterException.class})public ViewResult<Object> missingServletRequestParameterException(MissingServletRequestParameterException e) {return ViewResult.state(RpcCode.OPERATION_NOT_PERMITTED_CODE, e.getMessage(), null);}@ResponseStatus(HttpStatus.OK)@org.springframework.web.bind.annotation.ExceptionHandler(value = {Exception.class})public ViewResult<Object> allException(Exception e) {ViewResult<Object> result = buildCustomException(e);if (result == null && e.getCause() != null) {result = buildCustomException(e.getCause() );}if (result != null) {return result;}// 请求传参等spring抛出的异常消息显示出来用于调试if (e instanceof ServletException || e instanceof NestedRuntimeException) {log.warn("", e);return ViewResult.state(RpcCode.SYSTEM_DEFAULT_ERROR_CODE, "请求错误:" + e.getMessage(), null);}log.error("system error:", e);return ViewResult.state(RpcCode.SYSTEM_DEFAULT_ERROR, null);}/*** 自定义异常的统一处理,各异常的message需要是汉字形式的提示文本。* @param e* @return*/private ViewResult<Object> buildCustomException(Throwable e) {int code = RpcCode.SYSTEM_DEFAULT_ERROR_CODE;if (e instanceof NoAuthException) {code = RpcCode.OPERATION_NOT_PERMITTED_CODE;} else if (e instanceof com.chj.thor.auth.v2.exception.NoAuthException) {code = RpcCode.OPERATION_NOT_PERMITTED_CODE;} else if (e instanceof DuplicatedException) {code = RpcCode.RESOURCE_DUPLICATED_CODE;} else if (e instanceof NotFoundException) {code = RpcCode.RESOURCE_NOTFOUND_CODE;} else if (e instanceof OperationNotPermittedException) {code = RpcCode.OPERATION_NOT_PERMITTED_CODE;} else if (e instanceof ParamInvalidException) {code = ApiRpcCode.PARAM_INVALIDATED_CODE;} else if (e instanceof UrlUnreachableException) {code = ApiRpcCode.URL_UNREACHABLE_CODE;} else if (e instanceof ThirdServiceException) {code = ApiRpcCode.THIRD_SERVICE_CODE;} else if (e instanceof ThorException) {code = 500001;}if (code != RpcCode.SYSTEM_DEFAULT_ERROR_CODE) {return ViewResult.state(code, e.getMessage(), null);}return null;}@ResponseStatus(HttpStatus.BAD_REQUEST)@org.springframework.web.bind.annotation.ExceptionHandler({MethodArgumentNotValidException.class,//requestBody校验})public ViewResult<Object> methodArgumentNotValidException(MethodArgumentNotValidException e) throws MethodArgumentNotValidException {log.info("[前置条件校验失败]", e);Class<?> clazz = e.getParameter().getExecutable().getDeclaringClass();//只有Controller层的参数出现问题才进行封装处理,否则直接上抛if (clazz.getSimpleName().endsWith("Controller")) {FieldError fieldError = e.getBindingResult().getFieldError();String message = "INVALID PARAMS";if (null != fieldError) {message += ":" + fieldError.getField();message += ":" + fieldError.getDefaultMessage();}return ViewResult.state(IRpcCode.ILLEGAL_ARGUMENT_CODE, message, null);} else {throw e;}}@ResponseStatus(HttpStatus.BAD_REQUEST)@org.springframework.web.bind.annotation.ExceptionHandler({ConstraintViolationException.class //requestParam校验})public ViewResult<Object> constraintViolationException(ConstraintViolationException e) {log.info("[前置条件校验失败]", e);Set<ConstraintViolation<?>> validations = e.getConstraintViolations();StringBuilder message = new StringBuilder("INVALID PARAMS");//当配置的是failFast模式时,循环只会执行一遍for (ConstraintViolation<?> v : validations) {//只有Controller service层的参数出现问题才进行封装处理,否则直接上抛if (v.getRootBeanClass().getSimpleName().endsWith("Controller") ||v.getRootBeanClass().getSimpleName().endsWith("ServiceImpl")) {message.append(":");message.append(v.getPropertyPath());message.append(":");message.append(v.getMessage());} else {throw e;}}return ViewResult.state(IRpcCode.ILLEGAL_ARGUMENT_CODE, message.toString(), null);}@ResponseStatus(HttpStatus.BAD_REQUEST)@org.springframework.web.bind.annotation.ExceptionHandler({HttpMessageNotReadableException.class, //requestParam校验HttpRequestMethodNotSupportedException.class,//method不支持HttpMediaTypeException.class,//ContentType问题ServletRequestBindingException.class//数据绑定问题})public ViewResult<Object> constraintViolationException(Exception e) {log.info("[客户端数据格式错误]", e);return ViewResult.state(IRpcCode.ILLEGAL_ARGUMENT_CODE, e.getMessage(), null);}}
http://www.lryc.cn/news/208054.html

相关文章:

  • 【2023CANN训练营第二季】——通过一份入门级算子开发代码了解Ascend C算子开发流程
  • 建模仿真软件 Comsol Multiphysics mac中文版软件介绍
  • 深入理解强化学习——强化学习的历史:近代强化学习的发展
  • 移动端ViT新利器!苹果提出稀疏专家混合模型Mobile V-MoEs
  • 【linux系统】服务器安装Pycharm
  • 便利连锁:如何增加收益?教你一招轻松搞定!
  • STM32-程序占用内存大小计算
  • 鱼眼图像去畸变python / c++
  • 文心一言简单体验
  • css正确的语法
  • 【PG】PostgresSQL角色管理
  • 百度智能云获评Forrester中国市场人工智能/机器学习平台领导者
  • 基于java+swing+mysql实现的仓库商品管理系统
  • 深入理解Spring Boot AOP:CGLIB代理与JDK动态代理的完全指南
  • 【无标题】读书笔记之《智能化社会:未来人们如何生活、相爱和思考》
  • 华为云双十一服务器数据中心带宽全动态BGP和静态BGP区别
  • STM32 HAL库串口使用printf
  • 【VPX610】 青翼科技基于6U VPX总线架构的高性能实时信号处理平台
  • Parity 战略转型引热议,将如何推动波卡生态去中心化?
  • 【TES641】基于VU13P FPGA的4路FMC接口基带信号处理平台
  • Spring Kafka生产者实现
  • 手把手教你入门Three.js(初识篇)
  • Hadoop学习总结(搭建Hadoop集群(伪分布式模式))
  • 人性与理性共赢,真心罐头跃过增长的山海关
  • 【Redis】Docker部署Redis数据库
  • 【目标跟踪】多目标跟踪测距
  • 吐血整理,服务端性能测试-Docker部署MySQL/Nginx(详细步骤)
  • 基于单片机设计的智能窗帘控制系统
  • WSL的秘钥被修改了要怎么弄
  • cesium开发引入方式