我目前正在开发一个现有的系统,其中我必须为整个系统创建一个通用错误处理。该系统采用了Spring和AJAX。
现在,我已经完成了正常请求(不使用ajax)的错误处理,但是AJAX部分出现了问题。在AJAX部分中,如果存在错误/异常,页面不会重定向到我创建的泛型错误页。它停留在同一个屏幕上,什么都不会发生。
我已经对此进行了研究,似乎对于AJAX部分,我需要通过jQuery重定向来完成。
由于我使用的是现有的系统,所以我希望尽量减少所要做的更改。因此,我的问题是:是否有可能创建一个通用方法,AJAX部件可以在不向AJAX调用的“error:”部分添加额外代码的情况下自动调用该方法?
任何建议都会被欣然接受。:D
发布于 2014-08-26 04:11:24
您可以注册一个ajaxError事件。这里是jQuery的文档。
代码示例:
$( document ).ajaxError(function() {
//do your redirect(s) here
});和一个JSFiddle实例
注意,我只想简单地显示使用它的要点,但是您也可以得到哪个jqXHR对象抛出了错误/重新路由,这取决于它是哪一个。
发布于 2014-08-26 04:19:27
看看这里的通用错误处理
下面是我的应用程序中的工作示例。
我的ExceptionController
@ExceptionHandler(Exception.class)
public ModelAndView getExceptionPage(Exception e, HttpServletRequest request) {
BaseLoggers.exceptionLogger.error("Exception in Controller", e);
if (isAjax(request)) {
ModelAndView model = new ModelAndView("forward:/app/webExceptionHandler/ajaxErrorRedirectPage");
request.setAttribute("errorMessageObject", e.toString());
return model;
} else {
ModelAndView model = new ModelAndView("forward:/app/webExceptionHandler/nonAjaxErrorRedirectPage");
request.setAttribute("errorMessageObject", e.toString());
request.setAttribute("errorViewName", "error");
return model;
}
}转发请求的//AnotherController。
// this mapping is responsible for rendering view for all exceptions in nonAjax calls.
@RequestMapping(value = "/nonAjaxErrorRedirectPage")
public String nonAjaxErrorRedirectPage(HttpServletRequest request, Model model) {
Locale loc = RequestContextUtils.getLocale(request);
String nonAjaxErrorMsg = messageSource.getMessage("label.error.msg.nonAjaxCalls", null, loc);
model.addAttribute("errorMessage", nonAjaxErrorMsg);
String errorViewName = (String) request.getAttribute("errorViewName");
return errorViewName;
}
// this mapping is responsible for sending error message with suitable error code for all exceptions in Ajax calls.
@RequestMapping(value = "/ajaxErrorRedirectPage")
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public String ajaxErrorRedirectPage(HttpServletRequest request, Model model) {
Locale loc = RequestContextUtils.getLocale(request);
String ajaxErrorMsg = messageSource.getMessage("label.error.msg.ajaxCalls", null, loc);
return ajaxErrorMsg;
}https://stackoverflow.com/questions/25497820
复制相似问题