異なるオブジェクト・タイプを戻す異なるAPI呼び出しの例外を処理するために、単一のレスト・コントローラーを構成するにはどうすればよいですか?スプリング・レスト・コントローラーの例外処理
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Foo> method1()
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Bar> method2()
)のは、(法1()と方法2の両方を言ってみましょうMyExceptionのインスタンスをスローし、その後、私は異なり、以下の方法でそれらを処理する必要があります。
@ExceptionHandler(MyException.class)
@ResponseBody
public ResponseEntity<Foo> handleFoo(Exception ex) {
//Return foo with error description
Foo f = new Foo();
f.setError(ex.getMessage());
//Set f to response entity
return new ResponseEntity<>();
}
@ExceptionHandler(MyException.class)
@ResponseBody
public ResponseEntity<Bar> handleBar(Exception ex) {
//Return bar with error description
Bar b = new Bar();
b.setError(ex.getMessage());
//Set b to response entity
return new ResponseEntity<>();
}
法1()はMyExceptionのインスタンスをスローする場合、handleFoo()を呼び出す必要があります。 method2()では、handleBar()を呼び出す必要があります。
これは単一のレストコントローラで可能ですか、または各レストコントローラが2つ必要ですか?
例外の場合、 'ResponseEntity'または 'ResponseEntity 'を返す必要はありません。 Errorエンティティを1つ作成し、ResponseEntity のように返すことができます。 –
そうでなければ、それぞれのシナリオで2つの異なる例外をスローすることはできません。 – kuhajeyan