通过@ControllerAdvice和@ExceptionHandler实现全局异常处理,结合自定义BusinessException与统一ErrorResponse格式,提升代码可维护性与用户体验。1. 定义GlobalExceptionHandler类捕获NullPointerException、IllegalArgumentException及自定义异常;2. BusinessException包含code与message便于前端识别;3. 所有异常返回标准JSON结构;4. 异常处理按类型匹配,具体异常优先,兜底Exception避免系统崩溃,同时记录日志且不抛出新异常。

在Java开发中,特别是在使用Spring Boot构建的Web应用中,统一处理异常是提升代码可维护性和用户体验的重要手段。通过@ControllerAdvice和@ExceptionHandler,我们可以实现全局异常管理,避免在每个控制器中重复写try-catch块。
Spring提供了@ControllerAdvice注解,它是一个增强版的@Component,能够将一个类定义为全局异常处理器。结合@ExceptionHandler,可以捕获所有控制器中抛出的指定类型异常。
示例代码:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<String> handleNullPointer(NullPointerException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("发生了空指针异常:" + e.getMessage());
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Map<String, Object>> handleIllegalArgument(IllegalArgumentException e) {
Map<String, Object> response = new HashMap<>();
response.put("error", "参数非法");
response.put("message", e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}
// 处理自定义业务异常
@ExceptionHandler(BusinessException.class)
public ResponseEntity<ErrorResponse> handleBusinessException(BusinessException e) {
ErrorResponse error = new ErrorResponse(e.getCode(), e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
}
// 捕获未预期的其他异常
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGeneralException(Exception e) {
ErrorResponse error = new ErrorResponse("INTERNAL_ERROR", "系统内部错误");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
为了更好地表达业务场景中的错误,建议定义自己的异常类,比如BusinessException,并包含错误码和提示信息。
立即学习“Java免费学习笔记(深入)”;
示例:
public class BusinessException extends RuntimeException {
private String code;
public BusinessException(String code, String message) {
super(message);
this.code = code;
}
// getter方法
public String getCode() {
return code;
}
}
这样在业务逻辑中可以直接抛出带上下文信息的异常:
if (user == null) {
throw new BusinessException("USER_NOT_FOUND", "用户不存在");
}
前后端分离项目中,异常返回格式应保持一致,便于前端解析处理。
定义通用错误响应类:
public class ErrorResponse {
private String code;
private String message;
public ErrorResponse(String code, String message) {
this.code = code;
this.message = message;
}
// getter和setter省略
}
配合@ExceptionHandler返回该对象,前端收到JSON格式如:
{
"code": "USER_NOT_FOUND",
"message": "用户不存在"
}
Spring会根据异常类型的继承关系选择最匹配的方法。更具体的异常(如NullPointerException)优先于Exception被处理。
几点建议:
@ExceptionHandler(Exception.class)防止系统崩溃暴露细节log.error(),方便排查问题基本上就这些。合理使用@ControllerAdvice和@ExceptionHandler,能让异常管理变得集中、清晰、可控。不复杂但容易忽略。
以上就是在Java中如何使用ExceptionHandler统一处理异常_全局异常管理实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号