51单片机智能扫地吸尘智能车机器人红外避障风扇95(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码
2026/1/18 22:35:29
什么是全局异常处理?
为什么需要全局异常处理?
格式统一:
{code: 500, msg: "服务器内部错误", data: null})隐藏细节:
减少冗余:
try-catch便于调试:
@ControllerAdvice:
@Controller标注的类@ExceptionHandler:
@ExceptionHandler(NullPointerException.class)处理空指针异常实现流程
@ControllerAdvice的类中@ExceptionHandler标注的、匹配该异常类型的方法。定义统一响应结果类(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;}}定义自定义业务异常
packagecom.guslegend.exception;publicclassBusinessExceptionextendsRuntimeException{// 错误码privateIntegercode;// 构造方法:传入错误码和错误信息publicBusinessException(Integercode,Stringmessage){super(message);this.code=code;}// getterpublicIntegergetCode(){returncode;}}实现全局异常处理器(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,"服务器内部错误,请联系管理员");}}在业务中使用异常处理
@GetMapping("/error/{id}")publicResult<String>getUser(@PathVariableLongid){if(id==0){thrownewBusinessException(404,"用户不存在");}// 正常返回returnResult.success("用户信息:"+id);}查看测试结果