使用@ControllerAdvice和@ExceptionHandler实现全局异常处理,可捕获系统及自定义异常,避免信息暴露并统一响应格式;通过继承RuntimeException创建BizException类区分业务异常,并在全局处理器中返回结构化JSON数据;结合@RestControllerAdvice适用于前后端分离场景,提升系统健壮性与维护性。

在Java的Spring框架中,处理全局异常是提升系统健壮性和用户体验的重要环节。通过统一的异常处理机制,可以避免异常信息直接暴露给前端,同时减少代码重复。Spring提供了@ControllerAdvice和@ExceptionHandler注解来实现全局异常捕获与处理。
@ControllerAdvice是一个特殊的@Component,它能被Spring容器扫描到,并作用于所有@Controller标注的类。配合@ExceptionHandler,它可以集中处理跨控制器的异常。
创建一个全局异常处理类:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("系统发生错误:" + e.getMessage());
}
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<Map<String, Object>> handleNPE(NullPointerException e) {
Map<String, Object> response = new HashMap<>();
response.put("error", "空指针异常");
response.put("message", e.getMessage());
response.put("timestamp", System.currentTimeMillis());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}
}
这样,无论哪个控制器抛出指定类型的异常,都会被对应的方法捕获并返回统一格式的响应。
立即学习“Java免费学习笔记(深入)”;
实际开发中,通常会定义自己的业务异常类,比如BizException,便于区分系统异常和业务逻辑异常。
public class BizException extends RuntimeException {
private int code;
public BizException(int code, String message) {
super(message);
this.code = code;
}
// getter方法
public int getCode() { return code; }
}
然后在全局异常处理器中添加对该异常的处理:
@ExceptionHandler(BizException.class)
public ResponseEntity<Map<String, Object>> handleBizException(BizException e) {
Map<String, Object> response = new HashMap<>();
response.put("code", e.getCode());
response.put("message", e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}
在服务中可以直接抛出自定义异常,由全局处理器接管:
if (user == null) {
throw new BizException(1001, "用户不存在");
}
如果项目中主要使用@RestController(返回JSON数据),推荐使用@RestControllerAdvice,它是@ControllerAdvice和@ResponseBody的组合,自动将返回值序列化为JSON。
@RestControllerAdvice
public class ApiGlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public Map<String, Object> handleIllegalArgument(IllegalArgumentException e) {
Map<String, Object> result = new HashMap<>();
result.put("success", false);
result.put("msg", "参数不合法");
result.put("detail", e.getMessage());
return result;
}
}
这种方式更适合前后端分离架构,返回结构清晰的JSON错误信息,便于前端解析处理。
基本上就这些。通过合理使用Spring提供的全局异常处理机制,可以让项目更加规范、稳定,也更容易维护。关键是设计好异常分类和响应结构,做到错误可追踪、提示友好。
以上就是Java中Spring框架如何处理全局异常的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号