2016-09-20 7 views
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を使用

答えて

0

@ResponseStatus(HttpStatus.UNAUTHORIZED) 
    @ExceptionHandler({ UnAuthorizedException.class }) 
    public @ResponseBody ExceptionResponse unAuthorizedRequestException(final Exception exception) { 

     return response; 
    } 

@ResponseStatus(HttpStatus.CONFLICT) 
    @ExceptionHandler({ DuplicateDataException.class }) 
    public @ResponseBody ExceptionResponse DuplicateDataRequestException(final Exception exception) { 

     return response; 
    } 

@ResponseStatus(HttpStatus.BAD_REQUEST) 
    @ExceptionHandler({ InvalidException.class }) 
    public @ResponseBody ExceptionResponse handleInvalidException(final Exception exception) { 

     return response; 
    } 
+0

はこれよりも良い方法はありませんか? – user2340345

+0

これは、Spring例外ハンドラの動作方法です。あなたが春を使用している場合、これで行くことができます。 – Suraj

関連する問題