17370845950

java后端开发怎么处理Controller层的全局异常?
使用@ControllerAdvice和@ExceptionHandler实现全局异常处理,结合自定义异常类(如BusinessException)和@ResponseStatus注解,统一管理Controller层异常,提升代码可维护性与接口一致性。

在Java后端开发中,处理Controller层的全局异常通常使用 @ControllerAdvice@ExceptionHandler 注解来实现统一异常管理。这种方式可以避免在每个Controller中重复写异常捕获逻辑,提升代码可维护性。

1. 使用 @ControllerAdvice 统一处理异常

@ControllerAdvice 是一个全局异常处理器注解,作用于整个应用的所有Controller。它会拦截所有Controller抛出的未处理异常。

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

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity handleGenericException(Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("系统内部错误:" + e.getMessage());
    }

    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity> handleNPE(NullPointerException e) {
        Map response = new HashMap<>();
        response.put("error", "空指针异常");
        response.put("message", e.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }
}

2. 自定义业务异常并处理

实际项目中建议定义自己的业务异常类,比如 BusinessException,便于区分系统异常和业务逻辑异常。

定义自定义异常:

public class BusinessException extends RuntimeException {
    public BusinessException(String message) {
        super(message);
    }
}

在 Controller 中抛出:

@GetMapping("/user/{id}")
public User getUser(@PathVariable Long id) {
    if (id <= 0) {
        throw new BusinessException("用户ID不合法");
    }
    // ...
}

在全局处理器中添加对应处理方法:

@ExceptionHandler(BusinessException.class)
public ResponseEntity> handleBizException(BusinessException e) {
    Map response = new HashMap<>();
    response.put("code", 400);
    response.put("error", "业务异常");
    response.put("message", e.getMessage());
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}

3. 结合 @ResponseStatus 返回标准HTTP状态码

对于某些已知异常,可以直接用 @ResponseStatus 指定返回的状态码,简化响应逻辑。

例如:

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}

当抛出 ResourceNotFoundException 时,自动返回 404 状态码,无需在 handler 中额外设置。 基本上就这些。通过组合使用 @ControllerAdvice、@ExceptionHandler 和自定义异常,就能实现清晰、统一的Controller层异常处理机制,既保证接口返回格式一致,又方便前端解析错误信息。