Handle error 404 with Spring controller

后端 未结 5 547
再見小時候
再見小時候 2020-11-29 07:00

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

5条回答
  •  萌比男神i
    2020-11-29 07:34

    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:

    
       404
       /404error.html
    
    

    or

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

提交回复
热议问题