温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

spring如何处理异常

发布时间:2026-10-06 15:09:59 来源:亿速云 阅读:81 作者:小樊 栏目:编程语言

在 Spring(尤其是 Spring MVC / Spring Boot) 中,异常处理有多种方式,从简单到规范,常用的有以下几种:


一、局部异常处理(Controller 内)

1. @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 复用


二、全局异常处理(推荐)

2. @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
}

✅ 优点:

  • 全局统一
  • 可分类处理异常
  • 适合前后端分离项目

三、Spring 内置异常返回

3. 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 使用。


五、与 Spring 事务的关系(重要)

@Transactional
public void save() {
    throw new RuntimeException();
}
  • 默认只在 RuntimeException 时回滚
  • 受检异常(Exception)不会回滚
@Transactional(rollbackFor = Exception.class)

六、常见异常类型

异常 场景
IllegalArgumentException 参数错误
NullPointerException 空指针
MethodArgumentNotValidException 参数校验失败
AccessDeniedException 权限不足
HttpRequestMethodNotSupportedException 请求方式错误

七、推荐方案总结

✅ 实际项目推荐

  • @RestControllerAdvice
  • 自定义异常(BusinessException)
  • 统一返回结构
  • 日志记录(log.error)

如果你用的是 Spring Boot 版本 或 前后端分离 / 传统 MVC,我可以给你更具体的示例。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手