深圳建工集团青州网站建设优化排名
2026/1/8 19:49:32 网站建设 项目流程
深圳建工集团,青州网站建设优化排名,网站平台搭建要多少,天津行业建站一、 为什么要用 GlobalExceptionHandler#xff1f;#xff08;作用#xff09; 在传统的 Web 开发中#xff0c;我们经常会在 Controller 层看到大量的重复代码#xff1a; // ❌ 糟糕的代码示范 GetMapping(/user) public Result getUser() {try {userServ…一、 为什么要用 GlobalExceptionHandler作用在传统的 Web 开发中我们经常会在 Controller 层看到大量的重复代码// ❌ 糟糕的代码示范GetMapping(/user)publicResultgetUser(){try{userService.doSomething();returnResult.success();}catch(BusinessExceptione){returnResult.error(e.getCode(),e.getMessage());}catch(Exceptione){log.error(未知错误,e);returnResult.error(500,系统内部错误);}}这种写法有三个痛点代码冗余每个接口都要写一遍try-catch。格式不统一有的返回{code: 500}有的返回{status: error}前端处理起来非常痛苦。事务失效风险如果在catch块中吞掉了异常且没有手动回滚数据库事务可能提交脏数据。GlobalExceptionHandler的核心作用统一响应格式无论发生什么错误最终返回给前端的 JSON 结构永远是固定的如CommonResult。代码解耦业务逻辑Service/Controller只需关注“成功”的情况失败直接抛出异常由全局处理器兜底。保障事务让异常抛出 Service 层触发 Spring 的Transactional自动回滚保证数据一致性。集中日志管理在一个地方统一打印异常堆栈避免日志到处乱飞。二、 核心注解与原理用法要实现全局异常处理主要依赖两个注解RestControllerAdvice它是ControllerAdvice和ResponseBody的组合注解。含义拦截项目中所有 Controller 的异常并将处理结果直接以 JSON 格式返回。ExceptionHandler(Exception.class)含义标记在方法上声明该方法负责处理哪一种类型的异常。三、 实战代码示例示例以下是一个标准的企业级异常处理器模板。1. 定义统一返回对象首先我们需要一个标准的 JSON 包装类。DatapublicclassCommonResultT{privateIntegercode;privateStringmsg;privateTdata;publicstaticCommonResult?error(Integercode,Stringmsg){CommonResult?resultnewCommonResult();result.codecode;result.msgmsg;returnresult;}}2. 编写全局异常处理器Slf4jRestControllerAdvicepublicclassGlobalExceptionHandler{// 忽略的错误信息噪音过滤publicstaticfinalSetStringIGNORE_ERROR_MESSAGESSet.of(无效的刷新令牌);/** * 1. 处理自定义业务异常 (ServiceException) * 场景库存不足、账号密码错误 */ExceptionHandler(ServiceException.class)publicCommonResult?handleServiceException(ServiceExceptionex){// 只有不在忽略名单里的错误才打印日志避免刷屏if(!IGNORE_ERROR_MESSAGES.contains(ex.getMessage())){log.warn([业务异常] {},ex.getMessage());}returnCommonResult.error(ex.getCode(),ex.getMessage());}/** * 2. 处理参数校验异常 (JSON 格式) * 场景RequestBody Valid 校验失败 */ExceptionHandler(MethodArgumentNotValidException.class)publicCommonResult?handleMethodArgumentNotValidException(MethodArgumentNotValidExceptionex){// 从异常中提取第一个具体的错误提示StringerrorMessageex.getBindingResult().getFieldError().getDefaultMessage();log.warn([参数校验异常] {},errorMessage);returnCommonResult.error(400,String.format(请求参数不正确: %s,errorMessage));}/** * 3. 处理参数校验异常 (表单/URL 参数格式) * 场景GET 请求 Valid 校验失败 */ExceptionHandler(BindException.class)publicCommonResult?handleBindException(BindExceptionex){StringerrorMessageex.getBindingResult().getFieldError().getDefaultMessage();log.warn([参数绑定异常] {},errorMessage);returnCommonResult.error(400,String.format(请求参数不正确: %s,errorMessage));}/** * 4. 处理必填参数缺失 * 场景RequestParam 没传 */ExceptionHandler(MissingServletRequestParameterException.class)publicCommonResult?handleMissingServletRequestParameterException(MissingServletRequestParameterExceptionex){returnCommonResult.error(400,String.format(请求参数缺失: %s,ex.getParameterName()));}/** * 5. 兜底异常处理 (Exception) * 场景空指针、数据库连接超时、代码 Bug */ExceptionHandler(Exception.class)publicCommonResult?handleGlobalException(Exceptionex){// 这里必须打印 ERROR 级别的堆栈日志方便排查 Buglog.error([系统异常],ex);returnCommonResult.error(500,系统内部错误请联系管理员);}}四、 进阶如何处理 Filter 中的异常这是面试和实战中的高频考点。问题RestControllerAdvice只能捕获Controller 层之后的异常。如果Filter如 Token 认证过滤器抛出异常它是抓不到的。解决方案在yudao架构中通常会提供一个“手动分发器”方法。Filter 捕获异常后手动调用这个方法。代码片段// 在 GlobalExceptionHandler 中添加publicCommonResult?allExceptionHandler(HttpServletRequestrequest,Throwableex){if(exinstanceofServiceException){returnhandleServiceException((ServiceException)ex);}// ... 手动判断其他类型returnhandleGlobalException((Exception)ex);}// 在 Filter 中调用try{chain.doFilter(request,response);}catch(Exceptione){// 手动转交给全局异常处理器CommonResult?resultglobalExceptionHandler.allExceptionHandler(request,e);ServletUtils.writeJSON(response,result);}五、 总结GlobalExceptionHandler是 Spring Boot 工程化开发的基石。它像一个污水净化器输入各种乱七八糟的异常ServiceException, NullPointerException, ValidationException。处理记录日志、提取关键信息、过滤噪音。输出标准、干净、前端友好的 JSON 数据。通过它我们实现了后端代码的快速失败Service 层只需关注业务逻辑遇到问题直接抛异常剩下的全交给它处理。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询