Spring 3在App Engine中的错误处理(400)


问题内容

我想在我的App Engine应用程序中

处理错误400。我可以使用以下代码处理404错误:

@RequestMapping("/**")
public void unmappedRequest(HttpServletRequest request) {
    request.getRequestURI();
    String uri = request.getRequestURI();
    throw new UnknownResourceException("There is no resource for path "
    + uri);
}

然后我管理404错误。

但是,对于400错误(错误请求),我尝试了以下操作:

在web.xml中

  <error-page>
    <error-code>400</error-code>
    <location>/error/400</location>
  </error-page>

然后在我的控制器中

@RequestMapping("/error/400")
public void badRequest(HttpServletRequest request) {
    request.getRequestURI();
    String uri = request.getRequestURI();
    throw new UnknownResourceException("bad request for path " + uri);
}

但这是行不通的,因此当我提出错误请求时,我会从应用程序引擎获取默认错误屏幕。
有什么建议么?


问题答案:

我最终得到的最简单,最快的解决方案是执行以下操作:

@ControllerAdvice
public class ControllerHandler {

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public String handleMyException(Exception exception,
        HttpServletRequest request) {
    return "/error/myerror";
    }
}

此处的关键是处理org.springframework.web.bind。
MissingServletRequestParameterException ;

其他替代方法,也可以通过web.xml完成​​,如下所示:

<error-page>
    <exception-type>org.springframework.web.bind.MissingServletRequestParameterException</exception-type>
    <location>/WEB-INF/error/myerror.jsp</location>
</error-page>