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

查看:715
本文介绍了使用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.

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

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