咸阳市网站建设_网站建设公司_字体设计_seo优化
2026/1/18 21:11:28 网站建设 项目流程


文章目录

  • 第5章:SpringBoot 全局异常处理
    • SpringBoot全局异常介绍

第5章:SpringBoot 全局异常处理

SpringBoot全局异常介绍

什么是全局异常处理?

  • 集中捕获项目中所有未被手动捕获的异常;
  • 统一封装成前端可解析的 JSON 格式(如包含错误码、错误信息);
  • 替代默认的杂乱错误页面 / 堆栈信息。

为什么需要全局异常处理?

  • 格式统一:

    • 所有异常返回相同结构(如{code: 500, msg: "服务器内部错误", data: null}
    • 前端无需适配多种错误格式。
  • 隐藏细节:

    • 避免直接返回堆栈信息(含代码路径等敏感信息)
    • 提升安全性。
  • 减少冗余:

    • 无需在每个 Controller 方法中重复编写try-catch
    • 简化代码。
  • 便于调试:

    • 可在异常处理器中统一记录日志
    • 快速定位问题。

@ControllerAdvice

  • 标识一个 “全局增强类”
  • 作用于所有@Controller标注的类
  • 可用于全局异常处理、全局数据绑定等。

@ExceptionHandler

  • 标注在方法上
  • 指定该方法处理哪种类型的异常
  • @ExceptionHandler(NullPointerException.class)处理空指针异常

实现流程

  • 当 Controller 方法抛出异常且未手动捕获时,异常会被 Spring 框架捕获。
  • Spring 会查找标注了@ControllerAdvice的类中
  • 是否有@ExceptionHandler标注的、匹配该异常类型的方法。
  • 找到匹配的方法后,执行该方法
  • 将返回值(统一响应格式)返回给前端。
  1. 定义统一响应结果类(Result)

    packagecom.guslegend.common;importlombok.Data;@DatapublicclassResult<T>{// 状态码privateIntegercode;// 错误信息privateStringmsg;// 响应数据privateTdata;// 成功响应(带数据)publicstatic<T>Result<T>success(Tdata){Result<T>result=newResult<>();result.setCode(200);result.setMsg("success");result.setData(data);returnresult;}// 成功响应(无数据)publicstatic<T>Result<T>success(){returnsuccess(null);}// 错误响应publicstatic<T>Result<T>error(Integercode,Stringmsg){Result<T>result=newResult<>();result.setCode(code);result.setMsg(msg);result.setData(null);returnresult;}}
  2. 定义自定义业务异常

    packagecom.guslegend.exception;publicclassBusinessExceptionextendsRuntimeException{// 错误码privateIntegercode;// 构造方法:传入错误码和错误信息publicBusinessException(Integercode,Stringmessage){super(message);this.code=code;}// getterpublicIntegergetCode(){returncode;}}
  3. 实现全局异常处理器(GlobalExceptionHandler)

    packagecom.guslegend.exception;importcom.guslegend.common.Result;importlombok.extern.slf4j.Slf4j;importorg.springframework.web.bind.annotation.ControllerAdvice;importorg.springframework.web.bind.annotation.ExceptionHandler;importorg.springframework.web.bind.annotation.ResponseBody;@ControllerAdvice@Slf4jpublicclassGlobalExceptionHandler{/** * 处理自定义业务异常(优先级最高,先捕获业务异常) */@ExceptionHandler(BusinessException.class)@ResponseBody// 返回JSON格式publicResult<Void>handleBusinessException(BusinessExceptione){log.error("业务异常:{}",e.getMessage());returnResult.error(e.getCode(),e.getMessage());}/** * 处理系统异常(如空指针、数据库异常等,作为兜底处理) */@ExceptionHandler(Exception.class)@ResponseBodypublicResult<Void>handleSystemException(Exceptione){log.error("系统异常:",e);returnResult.error(500,"服务器内部错误,请联系管理员");}}
  4. 在业务中使用异常处理

    @GetMapping("/error/{id}")publicResult<String>getUser(@PathVariableLongid){if(id==0){thrownewBusinessException(404,"用户不存在");}// 正常返回returnResult.success("用户信息:"+id);}

查看测试结果


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

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

立即咨询