Spring MVC Spring Security and Error Handling

前端 未结 2 1959
孤独总比滥情好
孤独总比滥情好 2020-12-03 05:26

I\'m using ResponseEntityExceptionHandler for global handling the error and almost working normal, except I want to handle wrong request with spring. By any

相关标签:
2条回答
  • 2020-12-03 06:01

    throwExceptionIfNoHandlerFound take into account only if no handlers for request found.

    In case of default-servlet-handler was configured, DefaultServletHttpRequestHandler will handle request. So, if this solution doesn't work, remove it and have a look (debug) this place of DispatcherServlet.

    0 讨论(0)
  • 2020-12-03 06:15

    The reason is right there, in the DispatcherServlet class; it sends error response without bothering to call exception handler (by default).

    Since 4.0.0.RELEASE this behaviour can be simply changed with throwExceptionIfNoHandlerFound parameter:

    Set whether to throw a NoHandlerFoundException when no Handler was found for this request. This exception can then be caught with a HandlerExceptionResolver or an @ExceptionHandler controller method.

    XML configuration:

    <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>
    

    Java-based configuration:

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

    Then NoHandlerFoundException can be handled like this:

    @ControllerAdvice
    public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    
        @Override
        ResponseEntity handleNoHandlerFoundException(NoHandlerFoundException ex,
                HttpHeaders headers, HttpStatus status, WebRequest request) {
            // return whatever you want
        }
    }
    
    0 讨论(0)
提交回复
热议问题