3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SpringBootで/errorに対応する自作Controllerを作成する方法

Last updated at Posted at 2020-09-29

想定外の例外をログ出力するのに必要だったので、
SpringBootで/errorに対応する自作Controllerを作成する方法を調べた。

下記URLの通りにやれば可能。
https://www.logicbig.com/tutorials/spring-framework/spring-boot/implementing-error-controller.html

URLがリンク切れになった時ようにソースをコピペしておく。

@Controller
public class MyCustomErrorController implements ErrorController {

  @RequestMapping("/error")
  @ResponseBody
  public String handleError(HttpServletRequest request) {
      Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
      Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
      return String.format("<html><body><h2>Error Page</h2><div>Status code: <b>%s</b></div>"
                      + "<div>Exception Message: <b>%s</b></div><body></html>",
              statusCode, exception==null? "N/A": exception.getMessage());
  }

  @Deprecated
  @Override
  public String getErrorPath() {
      return "/error";
  }
}

APIの例外ハンドリングの情報は多いけど、この情報はなかなか出てこなかった。。

getErrorPathに@DeprecatedがないとGradleタスクのbootjar実行時にエラーになる
https://qiita.com/sakazoo/items/b4c9ae140df9d26e816f

3
0
1

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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?