4
6

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 5 years have passed since last update.

Springbootでエラー画面を表示する

Last updated at Posted at 2018-09-12

###Springbootでエラーが発生したときにエラー画面を表示するサンプルです。

1.Controller

エラー処理はControllerクラスに書きます。

ExceptionController.java
package com.stone.sample;

import java.util.Locale;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ExceptionController {
    @ExceptionHandler(NullPointerException.class)
    public String NullPointerExceptionHandler() {
        System.out.println("NullPointerException occured");
        return "error";
    }
    @ExceptionHandler(IllegalArgumentException.class)
    public String IllegalArgumentExceptionHandler() {
        System.out.println("IllegalArgumentException  occured");
        return "error";
    }
    @ExceptionHandler(Throwable.class)
    public String ThrowableHandler() {
        System.out.println("Exceotion  occured");
        return "error";
    }
    /**
     * このメソッドはテスト用です。
     */
    @RequestMapping(value = "/err", method = RequestMethod.GET)
    public String errorpage() throws Exception {
        throw new Exception();
    }
}

2.html

コントローラクラスでerrorをリターンしていますので、error.htmlを作成します。

error.html
<!DOCTYPE html>
<html>
<head>
    <title>error</title>
</head>
<body>
<h1>
    error!!
</h1>

</body>
</html>

3.確認

プロジェクトを実行してhttp://localhost:8080/err
にアクセスしてみます。

4.実行結果

image.png

エラー画面をハンドルできました。

4
6
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
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?