Springで自作のエラーページを表示する

ここではSpring組み込みのWEBサーバーを使用するのではなく別のサーバーにデプロイするケースを考える。つまりEmbeddedServletContainerCustomizerが使えないケース。

環境

Spring Boot 1.4 + Thymeleaf

やり方

以下は404 Not FoundでnotFound.html、401 Forbiddenでforbidden.html、それ以外のエラーでerror.htmlを表示するサンプル。

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class CustomErrorController extends AbstractErrorController {
    private static final String ERROR_PATH=  "/error";

    @Autowired
    public CustomErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @RequestMapping(ERROR_PATH)
    public String handleErrors(HttpServletRequest request, Model model) {
        HttpStatus status = getStatus(request);

        if (status.equals(HttpStatus.NOT_FOUND)) {
            return "notFound";
        }
        if (status.equals(HttpStatus.FORBIDDEN)) {
            return "forbidden";
        }
        
        model.addAttribute("exception", getErrorAttributes(request, true));
        return "error";
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}

補足

モデルにgetErrorAttributesで取得したエラー情報を渡しているのはerror.htmlにエラーの内容を表示するため。