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

Spring Boot全局异常处理:一网打尽Controller层异常,@RestControllerAdvice解析

在Spring Boot应用中,异常处理是构建健壮API的核心环节。

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

在传统Controller开发中,我们经常面临这样的困境:

@RestController
public class UserController {@GetMapping("/users/{id}")public User getUser(@PathVariable Long id) {try {return userService.findById(id);} catch (UserNotFoundException e) {// 重复的异常处理代码return new ErrorResponse("用户不存在");} catch (DatabaseException e) {// 每个Controller都要处理相同异常return new ErrorResponse("数据库错误");}}
}

痛点分析

  • 重复代码遍布各个Controller

  • 异常处理与业务逻辑耦合

  • 响应格式不统一

  • 维护成本高

二、@RestControllerAdvice 

1. 注解关系

2. 核心组件协作

三、Spring Boot 3 全局异常处理实战

1. 基础异常响应封装
public record ErrorResponse(Instant timestamp,int status,String error,String message,String path
) {public ErrorResponse(HttpStatus status, String message, String path) {this(Instant.now(), status.value(), status.getReasonPhrase(), message, path);}
}
2. 核心异常处理器实现
@RestControllerAdvice
public class GlobalExceptionHandler {// 处理自定义业务异常@ExceptionHandler(BusinessException.class)public ResponseEntity<ErrorResponse> handleBusinessException(BusinessException ex, WebRequest request) {return createResponse(HttpStatus.BAD_REQUEST, ex, request);}// 处理数据不存在异常@ExceptionHandler(EntityNotFoundException.class)public ResponseEntity<ErrorResponse> handleEntityNotFound(EntityNotFoundException ex, WebRequest request) {return createResponse(HttpStatus.NOT_FOUND, ex, request);}// 处理所有未捕获异常@ExceptionHandler(Exception.class)public ResponseEntity<ErrorResponse> handleAllExceptions(Exception ex, WebRequest request) {return createResponse(HttpStatus.INTERNAL_SERVER_ERROR, ex, request);}// 统一响应构建方法private ResponseEntity<ErrorResponse> createResponse(HttpStatus status, Exception ex, WebRequest request) {String path = ((ServletWebRequest) request).getRequest().getRequestURI();ErrorResponse body = new ErrorResponse(status, ex.getMessage(), path);return ResponseEntity.status(status).body(body);}
}
3. 自定义业务异常
public class BusinessException extends RuntimeException {public BusinessException(String message) {super(message);}
}

四、深度解析异常处理流程

1. 异常处理调用链

2. 异常匹配优先级

五、高级应用场景

1. 处理验证异常(Spring Validation)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public ErrorResponse handleValidationExceptions(MethodArgumentNotValidException ex) {Map<String, String> errors = new HashMap<>();ex.getBindingResult().getFieldErrors().forEach(error -> {String fieldName = error.getField();String message = error.getDefaultMessage();errors.put(fieldName, message);});return new ErrorResponse(HttpStatus.BAD_REQUEST,"验证失败",errors);
}
2. 处理安全异常(Spring Security)
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<ErrorResponse> handleAccessDenied(AccessDeniedException ex, WebRequest request) {String path = ((ServletWebRequest) request).getRequest().getRequestURI();ErrorResponse body = new ErrorResponse(HttpStatus.FORBIDDEN,"无权访问此资源",path);return ResponseEntity.status(HttpStatus.FORBIDDEN).body(body);
}

六、性能优化最佳实践

  1. 异常分类处理:精确匹配特定异常,避免使用过于宽泛的Exception.class

  2. 层次化异常结构

    // 基础业务异常
    public abstract class BaseException extends RuntimeException {private final ErrorCode errorCode;public BaseException(ErrorCode errorCode, String message) {super(message);this.errorCode = errorCode;}
    }// 具体业务异常
    public class PaymentException extends BaseException {public PaymentException(String message) {super(ErrorCode.PAYMENT_FAILED, message);}
    }

  3. 异常日志分级

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ErrorResponse> handleBusinessException(BusinessException ex, WebRequest request) {// 业务异常只记录DEBUG日志log.debug("Business exception occurred: {}", ex.getMessage());return createResponse(HttpStatus.BAD_REQUEST, ex, request);
    }@ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleAllExceptions(Exception ex, WebRequest request) {// 未知异常记录ERROR日志log.error("Unexpected error occurred", ex);return createResponse(HttpStatus.INTERNAL_SERVER_ERROR, ex, request);
    }

 七、实战

正常请求

GET /api/users/123
Status: 200 OK
Response: {"id":123,"name":"John Doe"}

 异常请求

GET /api/users/999
Status: 404 Not Found
Response: {"timestamp": "2023-08-20T10:15:30Z","status": 404,"error": "Not Found","message": "用户不存在","path": "/api/users/999"
}

验证失败请求

POST /api/users
Payload: {"name": "", "email": "invalid-email"}
Status: 400 Bad Request
Response: {"timestamp": "2023-08-20T10:18:45Z","status": 400,"error": "Bad Request","message": "验证失败","errors": {"name": "姓名不能为空","email": "邮箱格式不正确"}
}

八、总结

1、@RestControllerAdvice = @ControllerAdvice + @ResponseBody

  • 全局处理控制器异常
  • 响应体自动序列化(JSON/XML)

2、异常处理优先级

  • Controller局部处理器 > 全局处理器
  • 具体异常 > 通用异常

3.最佳实践

// 返回明确HTTP状态码
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(UserNotFoundException.class)// 使用ResponseEntity精确控制响应
@ExceptionHandler(PaymentException.class)
public ResponseEntity<ErrorResponse> handlePaymentException() {// 自定义响应头等复杂操作
}

4、生产环境建议

  • 禁用敏感错误信息(spring.mvc.include-error-details)
  • 自定义错误码体系
  • 异常国际化支持

So, 当再次处理错误时,应该能独挡一面了。当然,业务中,异常还应该有日志记录,如ES,traceInfo, 上下文等信息,便于排错.

 

http://www.lryc.cn/news/596904.html

相关文章:

  • Unreal5从入门到精通之使用 Python 编写虚幻编辑器脚本
  • Linux进程控制:掌握系统的核心脉络
  • 《设计模式之禅》笔记摘录 - 9.责任链模式
  • Xorg占用显卡内存问题和编译opencv GPU版本
  • 基于LNMP分布式个人云存储
  • Docker 容器中的 HEAD 请求缺失 header?从 Content-MD5 缺失聊起
  • BitDistiller:通过自蒸馏释放 Sub-4-Bit 大语言模型的潜力
  • BiLLM:突破大语言模型后训练量化的极限
  • AI安全“面壁计划”:我们如何对抗算法时代的“智子”封锁?
  • 主要分布在背侧海马体(dHPC)CA1区域(dCA1)的时间细胞对NLP中的深层语义分析的积极影响和启示
  • 使用 QLExpress 构建灵活可扩展的业务规则引擎
  • 糖尿病数据分析:血压与年龄关系可视化
  • OpenAI发布ChatGPT Agent,AI智能体迎来关键变革
  • Linux网络-------1.socket编程基础---(UDP-socket)
  • 基于数据挖掘的短视频点赞影响因素分析【LightGBM、XGBoost、随机森林、smote】
  • 应用层自定义协议【序列化+反序列化】
  • 2025暑期—06神经网络-常见网络
  • ChatGPT桌面版深度解析
  • 华为7月23日机考真题
  • TDengine 的 HISTOGRAM() 函数用户手册
  • 解决Spring事务中RPC调用无法回滚的问题
  • 解构未来金融:深入剖析DeFi与去中心化交易所(DEX)的技术架构
  • 【音视频学习】五、深入解析视频技术中的像素格式:颜色空间、位深度、存储布局
  • LoRA 低秩矩阵实现参数高效的权重更新
  • 新手向:Pycharm的使用技巧
  • python3写一个异步http接口服务调用大模型(async, sanic)---6.1
  • Hexo - 免费搭建个人博客04 - 创建另一个私人仓库,对Hexo项目进行版本管理
  • Log4j CVE-2021-44228 漏洞复现详细教程
  • Sklearn 机器学习 线性回归
  • 20250704-基于强化学习在云计算环境中的虚拟机资源调度研究