目前,我正试图在Spring项目中使用HandlerExceptionResolver进行异常处理。
我想通过resolveException处理正常的异常,通过handleNoSuchRequestHandlingMethod处理404的异常。
根据请求类型JSON或text/html,应该适当地返回异常响应。
resolveException现在可以工作了。
但是handleNoSuchRequestHandlingMethod让我头疼。从来没叫过!
根据docu,对于404错误,应该调用该方法。
http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolver.html
我做错什么了。
这就是我到目前为止所拥有的。
public class JsonExceptionResolver implements HandlerExceptionResolver {
protected final Log logger = LogFactory.getLog(getClass());
public ModelAndView resolveException(HttpServletRequest request,
if (exception instanceof NoSuchRequestHandlingMethodException) {
return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) exception, request, response, handler);
}
...
}
public ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException ex,
HttpServletRequest request,
HttpServletResponse response,
Object handler){
logger.info("Handle my exception!!!");
ModelAndView mav = new ModelAndView();
boolean isJSON = request.getHeader("Accept").equals("application/json");
if(isJSON){
...
}else{
..
}
return mav;
}
}用DefaultHandlerExceptionResolver编辑
public class MyExceptionResolver extends DefaultHandlerExceptionResolver {
protected final Log logger = LogFactory.getLog(getClass());
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
logger.warn("An Exception has occured in the application", exception);
logger.info("exception thrown " + exception.getMessage() );
if (exception instanceof NoSuchRequestHandlingMethodException) {
return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) exception, request, response, handler);
}
...
return mav;
}
public ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException ex,
HttpServletRequest request,
HttpServletResponse response,
Object handler){
logger.info("Handle my exception!!!");
ModelAndView mav = new ModelAndView();
boolean isJSON = request.getHeader("Accept").equals("application/json");
if(isJSON){
...
}else{
...
}
return mav;
}
}以上代码仍然没有效果。
还有其他想法吗?
发布于 2011-11-09 13:00:10
根据Spring的Juergen,HandlerExceptionResolver是不可能的,因为它只适用于子映射。
您有一个映射到/account/**的控制器,并从acount访问一个方法,在该方法中,不存在像/acount/notExists这样的映射。
我将为这个功能打开一个JIRA 改进票据。
编辑:
JIRA关于这个问题的票
发布于 2011-08-29 10:00:15
handleNoSuchRequestHandlingMethod不是HandlerExceptionResolver接口的一部分,所以只声明一个这个名称的方法就什么也做不了了。它是一个特定于DefaultHandlerExceptionResolver的受保护的方法,并从它的resolveException方法(它是接口的一部分)调用:
if (ex instanceof NoSuchRequestHandlingMethodException) {
return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) ex, request, response, handler);
}要再现相同的功能,可以将DefaultHandlerExceptionResolver子类并覆盖所需的方法,也可以在处理NoSuchRequestHandlingMethodException的resolveException方法中添加一个大小写。
https://stackoverflow.com/questions/7228622
复制相似问题