Spring MVC Spring Security and Error Handling

天大地大妈咪最大 提交于 2019-12-17 10:50:42

问题


I'm using ResponseEntityExceptionHandler for global handling the error and almost working normal, except I want to handle wrong request with spring. By any logic overriding handleNoSuchRequestHandlingMethod should handle this, but insted of handling always get

HTTP Status 404 -

type Status report

message

description The requested resource is not available.

Apache Tomcat/7.0.37

I just got this when enable debuging in console:

WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI

just to clarify by handling I mean I'm returning JSON.

any idea how to handle this?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/18322279/spring-mvc-spring-security-and-error-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!