Java中统一处理应用异常方法

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

在Java应用开发中,统一处理异常能提升代码的可维护性和用户体验。核心思路是通过全局异常处理机制捕获未被处理的异常,避免重复的try-catch代码,同时保证返回格式一致。

使用@ControllerAdvice和@ExceptionHandler

这是Spring Boot项目中最常见的统一异常处理方式。@ControllerAdvice注解的类会拦截所有控制器抛出的异常,结合@ExceptionHandler定义具体异常类型的响应逻辑。

示例:

创建一个全局异常处理器:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity handleBusinessException(BusinessException e) {
        ErrorResponse error = new ErrorResponse(e.getCode(), e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
    }

    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity handleNullPointer(NullPointerException e) {
        ErrorResponse error = new ErrorResponse("NULL_ERROR", "数据不能为空");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity handleUnexpectedException(Exception e) {
        ErrorResponse error = new ErrorResponse("INTERNAL_ERROR", "系统内部错误");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
    }
}

定义统一的错误响应结构

为了前端能一致地解析错误信息,建议封装统一的错误响应体。

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) {
throw new BusinessException("USER_NOT_FOUND", "用户不存在");
}

配合AOP或日志记录异常

可在全局异常处理器中加入日志输出,便于排查问题。

private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

@ExceptionHandler(Exception.class)
public ResponseEntity handleUnexpectedException(Exception e) {
    logger.error("未预期异常:", e);
    ErrorResponse error = new ErrorResponse("INTERNAL_ERROR", "系统内部错误");
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}

基本上就这些。合理使用@ControllerAdvice能大幅减少重复代码,让异常处理更集中、更可控。关键是要提前规划好异常分类和返回格式,团队协作时尤其重要。