使用Spring控制器处理错误404

使用Spring控制器处理错误404

问题描述:

我使用 @ExceptionHandler 来处理我的网络应用程序抛出的异常,在我的情况下,我的应用程序返回 JSON 响应使用 HTTP状态以获取对客户端的错误响应。

I use @ExceptionHandler to handle exceptions thrown by my web app, in my case my app returns JSON response with HTTP status for error responses to the client.

但是,我试图找出如何处理错误404 返回类似的JSON响应,例如处理的响应@ExceptionHandler

However, I am trying to figure out how to handle error 404 to return a similar JSON response like with the one handled by @ExceptionHandler

更新:

我的意思是,当访问不存在的网址时

I mean, when a URL that does not exist is accessed

最简单的方法是使用以下方法:

Simplest way to find out is use the following:

@ExceptionHandler(Throwable.class)
  public String handleAnyException(Throwable ex, HttpServletRequest request) {
    return ClassUtils.getShortName(ex.getClass());
  }

如果URL在DispatcherServlet的范围内,那么任何由错误输入或此方法将捕获任何其他内容,但如果输入的URL超出DispatcherServlet的URL映射,则必须使用:

If the URL is within the scope of DispatcherServlet then any 404 caused by mistyping or anything else will be caught by this method but if the URL typed is beyond the URL mapping of the DispatcherServlet then you have to either use:

<error-page>
   <exception-type>404</exception-type>
   <location>/404error.html</location>
</error-page>


为DispatcherServlet映射URL提供/映射,以便处理特定服务器实例的所有映射。

Provide "/" mapping to your DispatcherServlet mapping URL so as to handle all the mappings for the particular server instance.