使用@ControllerAdvice和@ExceptionHandler实现全局异常处理,通过定义统一的ErrorResponse结构和自定义BusinessException,结合日志记录,提升Java应用的可维护性与用户体验。

在Java应用开发中,统一处理异常能提升代码的可维护性和用户体验。核心思路是通过全局异常处理机制捕获未被处理的异常,避免重复的try-catch代码,同时保证返回格式一致。
这是Spring Boot项目中最常见的统一异常处理方式。@ControllerAdvice注解的类会拦截所有控制器抛出的异常,结合@ExceptionHandler定义具体异常类型的响应逻辑。
示例:创建一个全局异常处理器:
@ControllerAdvice
public class GlobalExceptionHandler {
@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(NullPointerException.class)
public ResponseEntity<ErrorResponse> handleNullPointer(NullPointerException e) {
ErrorResponse error = new ErrorResponse("NULL_ERROR", "数据不能为空");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleUnexpectedException(Exception e) {
ErrorResponse error = new ErrorResponse("INTERNAL_ERROR", "系统内部错误");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
为了前端能一致地解析错误信息,建议封装统一的错误响应体。
立即学习“Java免费学习笔记(深入)”;
public class ErrorResponse {
private String code;
private String message;
public ErrorResponse(String code, String message) {
this.code = code;
this.message = message;
}
// getter 和 setter 省略
}
通过继承RuntimeException创建业务异常,便于在服务层抛出并被全局捕获。
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) {<br>
throw new BusinessException("USER_NOT_FOUND", "用户不存在");<br>
}可在全局异常处理器中加入日志输出,便于排查问题。
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleUnexpectedException(Exception e) {
logger.error("未预期异常:", e);
ErrorResponse error = new ErrorResponse("INTERNAL_ERROR", "系统内部错误");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
基本上就这些。合理使用@ControllerAdvice能大幅减少重复代码,让异常处理更集中、更可控。关键是要提前规划好异常分类和返回格式,团队协作时尤其重要。
以上就是Java中统一处理应用异常方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号