LoginSignup
0

More than 5 years have passed since last update.

Spring 例外ハンドリング

Last updated at Posted at 2018-08-31

はじめに

Spring初心者です。
1.5ヶ月ほどで、Webアプリケーションを作りました。

例外処理について調べたので、まとめます。

HandlerExceptionResolver

これを使って例外処理をする。

以下の順番で処理されていく
@ExceptionHandlerを付与したメソッド
@ResponseStatusを付与したメソッド
③ Springで定義されている例外を処理するHandlerExceptionResolver
④ HandlerExceptionResolverを実装したクラス

個人制作の範疇ならば、①と②を使えば十分だった。

実際の使用例
@ExceptionHandler

Controller.java
@ExceptionHandler(Exception.class)
public String Handler(){catchしたExceptionの処理内容}

  
@ResponseStatus (クラスに@つけても大丈夫かも)

Controller.java
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public String Status(){例外処理}

例外を投げる

アプリケーション制作にあたり、以下のような役割にわけた。

  • @Controller
  • @Service
  • @Repository

理想としては、@Serviceでエラーを投げたかったが、できなかった。
おそらく@Controllerクラスで、各Serviceクラスを@Autowiredしてたから、
Controller側で処理するしかなかったと思っている。

もしかしたらServiceで処理できたのかもしれないな。。。

まとめ

慣れたら意外と、例外処理はできた。

@ControllerのスーパークラスにExceptionControllerなどを作って、
そこに各Exceptionの処理をまとめて記述した。
Controller単位でハンドリングしたい場合は、
都度Overrideすれば、余分な記述はなくなるかと。

ソースはGitHubに載っています。

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
0