404例外スプリングControllerAdviceに処理されません

レオナルドChirivì:

私は私が使用して、すべてのマップされていないURLを処理したいシンプルなSpring MVCのアプリケーションを持っています@ControllerAdviceここでは、コントローラは以下のとおりです。

@ControllerAdvice
public class ExceptionHandlerController {
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException.class)
    public String handle404() {
        return "exceptions/404page";
    }
}

それでも、すべての時間がホワイトレーベルのエラーページを取得します。

私が使用してみましたRuntimeException.classHttpStatus.BAD_REQUESTとしてクラス拡張NoHandlerFoundExceptionが、役に立たないし。

助言がありますか?

オイゲンCovaci:

それを動作させるためには、設定する必要がありthrowExceptionIfNoHandlerFoundDispecherServletのプロパティ。あなたがそれを行うことができます。

spring.mvc.throwExceptionIfNoHandlerFound=true

application.properties、ファイル、それ以外の要求は常にデフォルトサーブレットに転送され、NoHandlerFoundExceptionは、これまでにスローされます。

問題は、このような構成であっても、それは動作しません、です。ドキュメントから:

org.springframework.web.servlet.resource.DefaultServletHttpRequestHandlerが使用されている場合、要求は常にデフォルトサーブレットに転送され、NoHandlerFoundExceptionが、その場合にスローされることはありませんことに注意してください。

春ブーツがデフォルトで使用しているのでorg.springframework.web.servlet.resource.DefaultServletHttpRequestHandler、あなた自身を使用して、このメソッドをオーバーライドする必要がありますWebMvcConfigurer

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        // Do nothing instead of configurer.enable();
    }
} 

もちろん、上記のクラスは、より多くのあなたのケースで複雑になるかもしれません。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=171622&siteId=1