Spring异常处理-如何同时使用ExceptionResolver和@ExceptionHandler
作者:互联网
我开发了一个Web应用程序,其中表单验证异常应由@ExceptionHandler处理(需要灵活),而一般系统异常应由SimpleMappingExceptionResolver处理(执行诸如电子邮件通知之类的工作).
问题是,如果我同时使用,则为@ExceptionHandler映射的异常不会到达@ExceptionHandler,而是由ExceptionResolver捕获为defaultError.
知道如何做才能使其协同工作吗?
@ExceptionHandler(ValidatorException.class)
public String handleFormException(ValidatorException ex, ActionRequest actionRequest) {
logger.error(ex.getMessage());
//TODO make conditions
return "mainOrderForm";
}
@ActionMapping(params = "action=addDocOrder")
public void addDocOrder(@ModelAttribute("order") CstOrderBeanImpl orderBean,
BindingResult result, ActionRequest actionRequest, ActionResponse response)
throws PortalException, SystemException, ValidatorException {
logger.info("Adding Form Order");
Calendar cal = TimeUtils.getEuDeadLine(orderBean);
orderBean.setDeadLine(cal.getTime());
ValidatorException ve = validateService.validate(orderBean, result, actionRequest, validator);
if (ve != null) throw ve;
(...)
在DispatcherPortlet中,有
catch (Exception ex) {
// Trigger after-completion for thrown exception.
triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
(...)
哪个检查拦截器,但不存在,所以会执行默认操作…
我只是指出,这是Portlet环境,通常由参数驱动的“视图”较少.
解决方法:
也许作为ExceptionResolver中的一种解决方法,您可以动态调用您选择的处理程序方法.
public ModelAndView resolveException(RenderRequest req, RenderResponse res, Object handler,Exception exc) {
if(exc instanceof ValidatorException) {
try {
java.lang.reflect.Method m = handler.getClass().getMethod("someMethod", (Class<?>)null /* method parameters? */);
m.invoke(handler,new Object[]{(ValidatorException)exc,req/*, res - maybe?*/});
} catch(Exception e) {
// Handle exception
}
}
// Send email of the error etc..
}
这不是一个完美的解决方案,但应该可以工作.
标签:portlet,exception,spring 来源: https://codeday.me/bug/20191105/1996682.html