5

応答オブジェクトのエラーに従って、400、400、404 などの HTTPStatus コードを動的に返したいと考えています。私はこの質問に言及されました-Spring 3 restfulを使用してプログラムで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()));
    }

ExceptionUtilitygetMessageは、上記で使用した 2 つのメソッド (および)を持つクラス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 ?
    }
}

if 条件をチェックインしてそれに応じて応答コードを返したくありません。これを行うための他のより良い方法はありますか?

4

3 に答える 3

1

異なる例外に対して異なる例外ハンドラーを定義し@ResponseStatus、以下のように使用する必要があります。

@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;
    }

などは例ですInvalidException.classDuplicateDataException.classカスタム例外を定義して、コントローラー層からスローできます。たとえば、 を定義して、例外ハンドラからエラー コードUserAlreadyExistsExceptionを返すことができます。HttpStatus.CONFLICT

于 2016-09-20T08:39:32.810 に答える