用Spring控制器处理错误404

时间:2022-11-29 16:14:27

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.

我使用@ExceptionHandler来处理web应用程序抛出的异常,在我的例子中,我的应用程序以HTTP状态返回JSON响应,以响应客户机的错误响应。

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

但是,我正在尝试解决如何处理error 404返回类似于@ExceptionHandler处理的JSON响应的问题

Update:

更新:

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

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

5 个解决方案

#1


2  

Simplest way to find out is use the following:

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

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

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:

如果URL位于DispatcherServlet的范围内,那么该方法将捕获任何由错误输入或其他原因引起的404,但是如果URL类型超出了DispatcherServlet的URL映射,那么您必须使用以下两种方法:

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

or

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

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

#2


35  

I use spring 4.0 and java configuration. My working code is:

我使用spring 4.0和java配置。我的工作代码是:

@ControllerAdvice
public class MyExceptionController {
    @ExceptionHandler(NoHandlerFoundException.class)
    public ModelAndView handleError404(HttpServletRequest request, Exception e)   {
            ModelAndView mav = new ModelAndView("/404");
            mav.addObject("exception", e);  
            //mav.addObject("errorcode", "404");
            return mav;
    }
}

In JSP:

JSP:

    <div class="http-error-container">
        <h1>HTTP Status 404 - Page Not Found</h1>
        <p class="message-text">The page you requested is not available. You might try returning to the <a href="<c:url value="/"/>">home page</a>.</p>
    </div>

For Init param config:

Init参数配置:

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    public void customizeRegistration(ServletRegistration.Dynamic registration) {
        registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
    }
}

Or via xml:

或通过xml:

<servlet>
    <servlet-name>rest-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>

See Also: Spring MVC Spring Security and Error Handling

请参见:Spring MVC Spring Spring安全性和错误处理

#3


4  

With spring > 3.0 use @ResponseStatus

使用spring > 3.0使用@ResponseStatus。

  @ResponseStatus(value = HttpStatus.NOT_FOUND)
  public class ResourceNotFoundException extends RuntimeException {
    ...
}

    @Controller
    public class MyController {
    @RequestMapping.....
    public void handleCall() {
        if (isFound()) {
        // do some stuff
        }
        else {
              throw new ResourceNotFoundException(); 
        }
    }
}

#4


3  

public final class ResourceNotFoundException extends RuntimeException {

}


@ControllerAdvice
public class AppExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleNotFound() {
        return "404";
    }
}

Just define an Exception, an ExceptionHandler, throw the Exception from your business code controller.

只需定义一个异常,一个ExceptionHandler,从业务代码控制器中抛出异常。

#5


1  

You can use servlet standard way to handle 404 error. Add following code in web.xml

您可以使用servlet标准方式处理404错误。在web.xml中添加以下代码

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

#1


2  

Simplest way to find out is use the following:

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

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

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:

如果URL位于DispatcherServlet的范围内,那么该方法将捕获任何由错误输入或其他原因引起的404,但是如果URL类型超出了DispatcherServlet的URL映射,那么您必须使用以下两种方法:

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

or

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

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

#2


35  

I use spring 4.0 and java configuration. My working code is:

我使用spring 4.0和java配置。我的工作代码是:

@ControllerAdvice
public class MyExceptionController {
    @ExceptionHandler(NoHandlerFoundException.class)
    public ModelAndView handleError404(HttpServletRequest request, Exception e)   {
            ModelAndView mav = new ModelAndView("/404");
            mav.addObject("exception", e);  
            //mav.addObject("errorcode", "404");
            return mav;
    }
}

In JSP:

JSP:

    <div class="http-error-container">
        <h1>HTTP Status 404 - Page Not Found</h1>
        <p class="message-text">The page you requested is not available. You might try returning to the <a href="<c:url value="/"/>">home page</a>.</p>
    </div>

For Init param config:

Init参数配置:

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    public void customizeRegistration(ServletRegistration.Dynamic registration) {
        registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
    }
}

Or via xml:

或通过xml:

<servlet>
    <servlet-name>rest-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>

See Also: Spring MVC Spring Security and Error Handling

请参见:Spring MVC Spring Spring安全性和错误处理

#3


4  

With spring > 3.0 use @ResponseStatus

使用spring > 3.0使用@ResponseStatus。

  @ResponseStatus(value = HttpStatus.NOT_FOUND)
  public class ResourceNotFoundException extends RuntimeException {
    ...
}

    @Controller
    public class MyController {
    @RequestMapping.....
    public void handleCall() {
        if (isFound()) {
        // do some stuff
        }
        else {
              throw new ResourceNotFoundException(); 
        }
    }
}

#4


3  

public final class ResourceNotFoundException extends RuntimeException {

}


@ControllerAdvice
public class AppExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String handleNotFound() {
        return "404";
    }
}

Just define an Exception, an ExceptionHandler, throw the Exception from your business code controller.

只需定义一个异常,一个ExceptionHandler,从业务代码控制器中抛出异常。

#5


1  

You can use servlet standard way to handle 404 error. Add following code in web.xml

您可以使用servlet标准方式处理404错误。在web.xml中添加以下代码

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