Jer*_* S. 5 exception-handling spring-mvc http-status-code-404
我目前正在尝试HandlerExceptionResolver在Spring MVC项目中使用异常处理.
我想通过resolveException404的via
来处理正常的异常handleNoSuchRequestHandlingMethod.
根据请求类型JSON或text/html,应该适当地返回异常响应.
resolveException 现在有效.
但handleNoSuchRequestHandlingMethod让我头疼.从未打过电话!
根据文档,该方法应该调用404错误
我究竟做错了什么...
这就是我到目前为止所拥有的.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码仍无效.
还有其他想法吗?
根据 Spring 的 Juergen Hoeller 的说法,这是不可能的,HandlerExceptionResolver因为它只适用于子映射,例如
您有一个控制器映射到/account/**并从一个不存在映射的帐户访问一个方法,就像/acount/notExists它应该工作的那样。
我将为此功能开具 JIRA改进票
编辑:
关于此问题的 JIRA 票证
| 归档时间: |
|
| 查看次数: |
17796 次 |
| 最近记录: |