使用 @restcontrolleradvice 配合 @exceptionhandler(illegalstateexception.class) 即可捕获全局的非法状态异常。在方法中返回自定义的 json 响应对象,spring boot 会自动将其序列化为 http 响应体,从而统一处理程序中抛出的状态错误。

如何区分并处理不同类型的业务异常
通过定义多个 @ExceptionHandler 注解,可以针对不同的异常类型编写独立的处理方法。例如,除了捕获 IllegalStateException,还可以同时捕获 IllegalArgumentException,根据异常的具体子类或消息内容,返回不同的 HTTP 状态码和错误描述,实现更精细的错误控制。

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalStateException.class)
public Map<string object> handleIllegalState(IllegalStateException ex) {
Map<string object> body = new HashMap();
body.put("error", "Illegal State");
body.put("message", ex.getMessage());
return body;
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<string object> handleIllegalArg(IllegalArgumentException ex) {
Map<string object> body = new HashMap();
body.put("error", "Bad Request");
body.put("message", ex.getMessage());
return body;
}
}</string></string></string></string>
当异常发生在过滤器链中时如何处理
如果异常是在 Spring MVC 的 DispatcherServlet 之前,即在 Filter 或 Servlet 阶段抛出的,标准的 @ControllerAdvice 可能无法捕获。此时需要注册一个 ErrorController 或者配置 SimpleMappingExceptionResolver 来处理这些底层异常,确保所有路径上的错误都能被统一拦截。











