您可以在 Spring 中注册一个通用异常解析器来捕获所有异常并转换为您的error.jsp
.
使用由您的业务逻辑抛出的专用 RuntimeException,它有一个code
成员:
public class MyException extends RuntimeException {
private final Integer errorCode;
public MyException(String message, Throwable cause, int errorCode) {
super(message, cause);
this.errorCode = errorCode;
}
}
code
或者在异常消息中使用现有的 RuntimeException 实例。
提取code
和/或消息并相应地设置 HttpServletResponse 状态和 ModelAndView。
例如:
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME)
public class GenericHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
ModelAndView mav = new ModelAndView("error");
if (e instanceof MyException) {
MyException myException = (MyException) e;
String code = myException.getCode();
// could set the HTTP Status code
response.setStatus(HttpServletResponse.XXX);
// and add to the model
mav.addObject("code", code);
} // catch other Exception types and convert into your error page if required
return mav;
}
}