LoginSignup
5
7

More than 5 years have passed since last update.

springでパスに対応するハンドラが無い時に例外をスローさせてキャッチする

Posted at

spring-mvcでサーブレットマッピングに対応するパスが無い場合はログに以下のようなwarningが出る。この場合にspring側で例外をスローさせて、それを捕捉する。これにより(web.xmlではなくspringを使用した)404のハンドリングを行う。

[org.springframework.web.servlet.PageNotFound] (default task-2) No mapping found for HTTP request with URI [/xxxx] in DispatcherServlet with name 'dispatcher'

環境

  • WildFly 10.1.0.Final
  • org.springframework 4.3.8.RELEASE

コード

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebMVCApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        Class<?>[] configurations = {AppConfiguration.class};
        return configurations;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        Class<?>[] configs = {};
        return configs;
    }

    @Override
    protected String[] getServletMappings() {
        String[] mappings = {"/"};
        return mappings;
    }

    @Override
    protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
        DispatcherServlet dispatcherServlet = (DispatcherServlet)super.createDispatcherServlet(servletAppContext);
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        return dispatcherServlet;
    }
}

setThrowExceptionIfNoHandlerFoundにtrueを設定することで、リクエストに対応するハンドラが見当たらない場合に例外がスローされるようになる。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

@RestControllerAdvice
public class NoHandlerFoundControllerAdvice {
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseEntity<String> handleNoHandlerFoundException(NoHandlerFoundException ex) {
        return new ResponseEntity<>("not found", HttpStatus.NOT_FOUND);
    }
}

複数コントローラー間で共通な例外処理を記述するためにControllerAdvice(かControllerAdvice)を付与するクラスを作る。springはパスに対応するハンドラが無いとNoHandlerFoundExceptionをスローするようにさっき設定したので、これをExceptionHandlerに指定する。

情報源

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7