使用 Spring 控制器处理错误 404 [英] Handle error 404 with Spring controller

查看:25
本文介绍了使用 Spring 控制器处理错误 404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 @ExceptionHandler 来处理我的网络应用程序抛出的异常,在我的例子中,我的应用程序返回 JSON 响应和 HTTP status 错误对客户的回应.

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.

但是,我想弄清楚如何处理 error 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

更新:

我的意思是,当一个不存在的 URL 被访问时

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 的范围内,那么任何由输入错误或其他任何原因引起的 404 都会被此方法捕获,但如果键入的 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.

这篇关于使用 Spring 控制器处理错误 404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆