在 Spring(尤其是 Spring MVC / Spring Boot) 中,异常处理有多种方式,从简单到规范,常用的有以下几种:
@ExceptionHandler只在当前 Controller 中生效。
@RestController
public class UserController {
@GetMapping("/user/{id}")
public User getUser(@PathVariable Long id) {
if (id == null) {
throw new IllegalArgumentException("id不能为空");
}
return new User();
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
✅ 优点:简单
❌ 缺点:不能跨 Controller 复用
@ControllerAdvice + @ExceptionHandler最常用方式,统一管理异常。
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<ErrorResult> handleIllegalArgument(IllegalArgumentException e) {
return ResponseEntity.badRequest()
.body(new ErrorResult(400, e.getMessage()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResult> handleException(Exception e) {
return ResponseEntity.status(500)
.body(new ErrorResult(500, "系统异常"));
}
}
class ErrorResult {
private int code;
private String message;
// getter / setter / constructor
}
✅ 优点:
ResponseStatusException(Spring 5+)适合简单场景。
@GetMapping("/order/{id}")
public Order getOrder(@PathVariable Long id) {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "订单不存在");
}
✅ 不需要额外 Handler
❌ 不适合复杂异常结构
{
"code": 400,
"message": "参数错误",
"data": null
}
配合 RestControllerAdvice 使用。
@Transactional
public void save() {
throw new RuntimeException();
}
@Transactional(rollbackFor = Exception.class)
| 异常 | 场景 |
|---|---|
IllegalArgumentException |
参数错误 |
NullPointerException |
空指针 |
MethodArgumentNotValidException |
参数校验失败 |
AccessDeniedException |
权限不足 |
HttpRequestMethodNotSupportedException |
请求方式错误 |
✅ 实际项目推荐
@RestControllerAdviceBusinessException)log.error)如果你用的是 Spring Boot 版本 或 前后端分离 / 传统 MVC,我可以给你更具体的示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。