通过@controlleradvice和@exceptionhandler实现全局异常处理,结合自定义业务异常、responsestatus注解及验证异常捕获,可统一返回结构化错误信息,提升接口健壮性与用户体验。

在Java的Web开发中,特别是在使用Spring或Spring Boot框架时,统一处理Web请求异常可以极大提升代码的可维护性和用户体验。通过@ControllerAdvice和@ExceptionHandler注解,我们可以实现全局异常集中管理,避免在每个控制器中重复写异常捕获逻辑。
1. 使用@ControllerAdvice和@ExceptionHandler处理异常
Spring提供了@ControllerAdvice注解,用于定义全局异常处理器。它能拦截所有控制器抛出的异常,并通过@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> error = new HashMap<>();
error.put("error", "参数错误");
error.put("message", e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleGeneralException(Exception e) {
Map<String, Object> error = new HashMap<>();
error.put("error", "服务器内部错误");
error.put("message", e.getClass().getSimpleName() + ": " + e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
上述代码中,不同类型的异常由不同的方法处理,返回结构化的错误响应。最通用的Exception.class放在最后,作为兜底处理。
立即学习“Java免费学习笔记(深入)”;
2. 自定义业务异常并统一处理
在实际项目中,建议定义自己的业务异常类,便于区分系统异常和业务逻辑异常。
public class BusinessException extends RuntimeException {
public BusinessException(String message) {
super(message);
}
}
然后在全局异常处理器中添加对应处理方法:
@ExceptionHandler(BusinessException.class)
public ResponseEntity<Map<String, Object>> handleBusinessException(BusinessException e) {
Map<String, Object> response = new HashMap<>();
response.put("error", "业务异常");
response.put("message", e.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}
这样在Service或Controller中可以直接抛出throw new BusinessException("用户名已存在"),由全局处理器统一响应。
3. 结合ResponseStatus注解简化处理
除了在@ExceptionHandler中手动设置HTTP状态码,也可以在自定义异常上使用@ResponseStatus注解,自动映射状态码。
@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "权限不足")
public class AccessDeniedException extends RuntimeException {
public AccessDeniedException(String message) {
super(message);
}
}
只要这个异常被抛出,Spring会自动返回403状态码,无需在@ExceptionHandler中再指定状态。
4. 处理验证异常(如MethodArgumentNotValidException)
当使用@Valid进行参数校验时,若校验失败会抛出MethodArgumentNotValidException。可以在全局处理器中捕获并提取错误字段信息。
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, Object>> handleValidationException(MethodArgumentNotValidException e) {
Map<String, Object> errors = new HashMap<>();
errors.put("error", "参数校验失败");
List<String> messages = e.getBindingResult()
.getFieldErrors()
.stream()
.map(FieldError::getDefaultMessage)
.collect(Collectors.toList());
errors.put("messages", messages);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
}
这样前端能收到具体的字段错误提示,提升交互体验。
基本上就这些。通过合理使用@ControllerAdvice和@ExceptionHandler,配合自定义异常和验证处理,可以实现清晰、统一的Web异常响应机制,让后端接口更健壮、易维护。










