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

SpringMVC @ExceptionHandler 典型用法

处理单个异常类型

当 getUser() 方法抛出 UserNotFoundException 时,会自动调用 handleUserNotFound() 方法进行处理。

@RestController
@RequestMapping("/users")
public class UserController {@GetMapping("/{id}")public User getUser(@PathVariable Long id) {// 可能抛出 UserNotFoundExceptionreturn userService.getUserById(id);}@ExceptionHandler(UserNotFoundException.class)public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());}
}

处理多个异常类型

一个 @ExceptionHandler 方法可以处理多个异常类型:

@ExceptionHandler({IllegalArgumentException.class, ResourceNotFoundException.class})
public ResponseEntity<String> handleClientErrors(RuntimeException ex) {return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("客户端错误: " + ex.getMessage());
}

结合 @ResponseStatus 使用(返回指定状态码)

此时返回值直接作为响应体,HTTP 状态码由 @ResponseStatus 指定。

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleResourceNotFound(ResourceNotFoundException ex) {return ex.getMessage();
}

返回结构化错误信息(推荐做法)

@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) {ErrorResponse error = new ErrorResponse(HttpStatus.NOT_FOUND.value(), ex.getMessage(), LocalDateTime.now());return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
}// ErrorResponse 示例类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ErrorResponse {private int status;private String message;private LocalDateTime timestamp;
}

捕获所有异常(兜底处理)

注意顺序:更具体的异常应放在前面,避免被 Exception.class 拦截。

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse handleAllExceptions(Exception ex) {return new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统内部错误", ex.getMessage(), LocalDateTime.now());
}

不同返回类型

@ExceptionHandler 方法可以有多种返回类型,如 String, ResponseEntity, Map, 自定义 DTO 等。

@RestController
@RequestMapping("/users")
public class UserController {@GetMapping("/{id}")public User getUser(@PathVariable Long id) {if (id == null || id <= 0) {throw new IllegalArgumentException("用户 ID 不合法");}// ...}@ExceptionHandler(IllegalArgumentException.class)@ResponseStatus(HttpStatus.BAD_REQUEST)public String handleIllegalArgument(IllegalArgumentException ex) {return "参数错误:" + ex.getMessage();}@ExceptionHandler(UserNotFoundException.class)public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) {ErrorResponse error = new ErrorResponse(404, ex.getMessage(), LocalDateTime.now());return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);}@ExceptionHandler(Exception.class)@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)public ErrorResponse handleAllExceptions(Exception ex) {return new ErrorResponse(500, "系统错误", ex.getMessage(), LocalDateTime.now());}
}
http://www.dtcms.com/a/271815.html

相关文章:

  • 了解去中心化金融在现代经济中的作用——安全交易新时代
  • 编写bat文件自动打开chrome浏览器,并通过selenium抓取浏览器操作chrome
  • 双指针-18.四数之和-力扣(LeetCode)
  • linux系统---ISCSI存储服务
  • Language Models are Few-Shot Learners: 开箱即用的GPT-3(二)
  • 节点小宝:手机图片备份至电脑功能实测体验
  • 同一类型,每条数据,执行不同逻辑
  • 偏振相机,偏振图像是怎么样的
  • WebGPU了解
  • 智能体决策机制深度剖析:ReAct、Plan-and-Execute与自适应策略
  • 云蝠智能VoiceAgent重构企业电话客服体系
  • PLC框架-1.3.2 报文750控制汇川伺服的转矩上下限
  • 【前缀和 BFS 并集查找】P3127 [USACO15OPEN] Trapped in the Haybales G|省选-
  • XSS(跨站脚本攻击)
  • RabbitMQ 消息队列:从入门到Spring Boot实战
  • Java 枚举详解:从基础到实战,掌握类型安全与优雅设计
  • 7-语言模型
  • CRT 不同会导致 fopen 地址不同
  • 技术演进中的开发沉思-30 MFC系列:五大机制
  • 删除k8s安装残留
  • Spring Boot:将应用部署到Kubernetes的完整指南
  • ACL协议:核心概念与配置要点解析
  • Docker 环境下 MySQL 主从复制集群、MGR 搭建及 Nginx 反向代理配置
  • SSRF10 各种限制绕过之30x跳转绕过协议限制
  • ip地址可以精确到什么级别?如何获取/更改ip地址
  • 配置双网卡Linux主机作为路由器(连接NAT网络和仅主机模式网络)
  • 在 Mac 上使用 Git 拉取项目:完整指南
  • 【算法笔记】6.LeetCode-Hot100-链表专项
  • selenium中find_element()用法进行元素定位
  • 在mac m1基于llama.cpp运行deepseek