0
レスポンスオブジェクトのrエラーに応じて400,400,404などのHTTPStatusコードを動的に返すようにします。 Iveはこの質問を参照しました - Programmatically change http response status using spring 3 restfulしかし、それは助けにはなりません。@ExceptionHandlerを使用してリクエストごとにHTTPステータスコードを動的に返します
アイブ@ExceptionHandler方法
@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseEntity<?> handleException(CustomException e) {
return new ResponseEntity<MyErrorResponse>(
new MyErrorResponse(e.getCode(), ExceptionUtility.getMessage(e.getMessage())),
ExceptionUtility.getHttpCode(e.getCode()));
}
ExceptionUtilityは、私は上記の私がチェックインしたくない二つの方法=のgetMessageとにgetCode
public class ExceptionUtility {
public static String getMessage(String message) {
return message;
}
public static HttpStatus getHttpCode(String code) {
return HttpStatus.NOT_FOUND; //how to return status code dynamically here ?
}
を使用していたクラスであると、このコントローラクラス条件が満たされていればそれに応じてレスポンスコードを返します。これを行うための他のより良いアプローチがありますか?あなたが別の例外のために別の例外ハンドラを定義する必要があり、その後、以下のように@ResponseStatus
を使用
はこれよりも良い方法はありませんか? – user2340345
これは、Spring例外ハンドラの動作方法です。あなたが春を使用している場合、これで行くことができます。 – Suraj