你可以在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;
}
}
或者依賴於異常消息現有RuntimeException的情況下與你code
。
提取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;
}
}