設定throwExceptionIfNoHandlerFound
は Spring 4.2.2 では効果がありません。すべての応答を JSON として送信する必要があるため、これは私にとって重要です。
私はAppInitializerthrowExceptionIfNoHandlerFound
でそのように設定しています:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
[...]
@Override
protected void customizeRegistration(Dynamic registration) {
boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); // -> true
if(!done) throw new RuntimeException();
}
}
DispatcherServlet#noHandlerFoundが期待どおりに例外をスローするため、機能しているようです。
// https://github.com/spring-projects/spring-framework/blob/4.2.x/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java#L1013
protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (pageNotFoundLogger.isWarnEnabled()) {
pageNotFoundLogger.warn("No mapping found for HTTP request with URI [" + getRequestUri(request) +
"] in DispatcherServlet with name '" + getServletName() + "'");
}
if (this.throwExceptionIfNoHandlerFound) {
throw new NoHandlerFoundException(request.getMethod(), getRequestUri(request),
new ServletServerHttpRequest(request).getHeaders());
}
else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
しかし、その後(非常に紛らわしいです!)すべての例外がキャッチされ、エラービューに解決されます。NoHandlerFoundException
そのため、 Spring を使用して処理することはできません。@ExceptionHandler
質問:
確かに、これは非常に便利で便利な機能ですが、404 エラーを検出して、デフォルトの HTML エラー ページの代わりにカスタム応答を送信する方法はありますか?