在java web应用中,实现全局异常处理的核心做法是定义一个被 @controlleradvice 注解的类,并在其中使用 @exceptionhandler 捕获特定或通用的异常。通过这种方式,可以统一拦截控制器层抛出的异常,将其转换为标准的json响应或错误页面,从而避免默认的tomcat错误页暴露敏感信息并提升用户体验。

如何配置全局异常处理器类?
需要创建一个继承自 ResponseEntityExceptionHandler 或直接标注 @RestControllerAdvice 的组件类。该类会自动扫描所有控制器中抛出的异常,并根据异常类型进行匹配处理。开发者只需在方法上指定要捕获的异常类,即可接管该异常的响应逻辑。

import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAllExceptions(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("系统内部错误: " + e.getMessage());
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArg(IllegalArgumentException e) {
return ResponseEntity.badRequest()
.body("参数错误: " + e.getMessage());
}
}
如何处理自定义业务异常?
对于特定的业务逻辑错误(如用户不存在、权限不足),建议定义自定义异常类并在全局处理器中单独捕获。这样可以返回更精确的状态码和错误信息,而不是统一返回500错误。通过区分不同业务场景的异常,前端可以根据状态码或错误消息做出不同的交互反馈。
立即学习“Java免费学习笔记(深入)”;

import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) { super(message); }
}
@RestControllerAdvice
public class BusinessExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFound(UserNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body("用户未找到: " + e.getMessage());
}
}
当抛出RuntimeException时全局处理器会如何响应?
当控制器中抛出未检查的 RuntimeException 且未被局部try-catch包裹时,全局异常处理器中的 @ExceptionHandler(Exception.class) 方法会被触发。此时,程序会跳过正常的视图渲染或数据返回流程,直接执行处理器中的逻辑,返回预设的错误响应体。这种机制确保了即使发生运行时错误,应用也能保持稳定的输出格式。


















