REST APIのカスタムエラーメッセージ処理

REST APIのカスタムエラーメッセージ処理

1. 概要

このチュートリアルでは、Spring RESTAPIのグローバルエラーハンドラーを実装する方法について説明します。

各例外のセマンティクスを使用して、クライアントに意味のあるエラーメッセージを作成し、そのクライアントにすべての情報を提供して問題を簡単に診断するという明確な目標を設定します。

参考文献:

Spring ResponseStatusException

ResponseStatusExceptionでSpringのHTTP応答にステータスコードを適用する方法を学びます。

SpringでのRESTのエラー処理

REST APIの例外処理-新しいSpring 3.2推奨アプローチと以前のソリューションを示します。

2. カスタムエラーメッセージ

まず、ネットワークを介してエラーを送信するための単純な構造、ApiErrorを実装することから始めましょう。

public class ApiError {

    private HttpStatus status;
    private String message;
    private List errors;

    public ApiError(HttpStatus status, String message, List errors) {
        super();
        this.status = status;
        this.message = message;
        this.errors = errors;
    }

    public ApiError(HttpStatus status, String message, String error) {
        super();
        this.status = status;
        this.message = message;
        errors = Arrays.asList(error);
    }
}

ここの情報は簡単なはずです:

  • status:HTTPステータスコード

  • message:例外に関連するエラーメッセージ

  • error:作成されたエラーメッセージのリスト

そしてもちろん、Springの実際の例外処理ロジックの場合、we’ll use@ControllerAdviceアノテーションです。

@ControllerAdvice
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {
    ...
}

3. 不正なリクエストの例外を処理する

3.1. 例外の処理

次に、最も一般的なクライアントエラーを処理する方法を見てみましょう。基本的に、クライアントが無効なリクエストをAPIに送信したシナリオです。

  • BindException:この例外は、致命的なバインディングエラーが発生した場合にスローされます。

  • MethodArgumentNotValidException:この例外は、@Validで注釈が付けられた引数が検証に失敗した場合にスローされます。

@Override
protected ResponseEntity handleMethodArgumentNotValid(
  MethodArgumentNotValidException ex,
  HttpHeaders headers,
  HttpStatus status,
  WebRequest request) {
    List errors = new ArrayList();
    for (FieldError error : ex.getBindingResult().getFieldErrors()) {
        errors.add(error.getField() + ": " + error.getDefaultMessage());
    }
    for (ObjectError error : ex.getBindingResult().getGlobalErrors()) {
        errors.add(error.getObjectName() + ": " + error.getDefaultMessage());
    }

    ApiError apiError =
      new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errors);
    return handleExceptionInternal(
      ex, apiError, headers, apiError.getStatus(), request);
}


ご覧のとおり、we are overriding a base method out of the ResponseEntityExceptionHandler and providing our own custom implementationです。

これが常に当てはまるとは限りません。後で説明するように、基本クラスにデフォルトの実装がないカスタム例外を処理する必要がある場合があります。

次:

  • MissingServletRequestPartException:この例外は、マルチパートリクエストの一部が見つからない場合にスローされます

  • MissingServletRequestParameterException:この例外は、リクエストにパラメータがない場合にスローされます。

@Override
protected ResponseEntity handleMissingServletRequestParameter(
  MissingServletRequestParameterException ex, HttpHeaders headers,
  HttpStatus status, WebRequest request) {
    String error = ex.getParameterName() + " parameter is missing";

    ApiError apiError =
      new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
    return new ResponseEntity(
      apiError, new HttpHeaders(), apiError.getStatus());
}


  • ConstrainViolationException:この例外は、制約違反の結果を報告します。

@ExceptionHandler({ ConstraintViolationException.class })
public ResponseEntity handleConstraintViolation(
  ConstraintViolationException ex, WebRequest request) {
    List errors = new ArrayList();
    for (ConstraintViolation violation : ex.getConstraintViolations()) {
        errors.add(violation.getRootBeanClass().getName() + " " +
          violation.getPropertyPath() + ": " + violation.getMessage());
    }

    ApiError apiError =
      new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errors);
    return new ResponseEntity(
      apiError, new HttpHeaders(), apiError.getStatus());
}


  • TypeMismatchException:この例外は、Beanプロパティを間違ったタイプに設定しようとするとスローされます。

  • MethodArgumentTypeMismatchException:この例外は、メソッド引数が予期されたタイプではない場合にスローされます。

@ExceptionHandler({ MethodArgumentTypeMismatchException.class })
public ResponseEntity handleMethodArgumentTypeMismatch(
  MethodArgumentTypeMismatchException ex, WebRequest request) {
    String error =
      ex.getName() + " should be of type " + ex.getRequiredType().getName();

    ApiError apiError =
      new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
    return new ResponseEntity(
      apiError, new HttpHeaders(), apiError.getStatus());
}



3.2. クライアントからのAPIの消費

ここで、MethodArgumentTypeMismatchExceptionに遭遇するテストを見てみましょう。send a request with id as String instead of long

@Test
public void whenMethodArgumentMismatch_thenBadRequest() {
    Response response = givenAuth().get(URL_PREFIX + "/api/foos/ccc");
    ApiError error = response.as(ApiError.class);

    assertEquals(HttpStatus.BAD_REQUEST, error.getStatus());
    assertEquals(1, error.getErrors().size());
    assertTrue(error.getErrors().get(0).contains("should be of type"));
}

そして最後に、この同じリクエストを検討します::

Request method:  GET
Request path:   http://localhost:8080/spring-security-rest/api/foos/ccc

この種のJSONエラー応答は次のようになります。

{
    "status": "BAD_REQUEST",
    "message":
      "Failed to convert value of type [java.lang.String]
       to required type [java.lang.Long]; nested exception
       is java.lang.NumberFormatException: For input string: \"ccc\"",
    "errors": [
        "id should be of type java.lang.Long"
    ]
}

4. NoHandlerFoundExceptionを処理する

次に、次のように、404応答を送信する代わりにこの例外をスローするようにサーブレットをカスタマイズできます。


    api
    
      org.springframework.web.servlet.DispatcherServlet
    
        throwExceptionIfNoHandlerFound
        true
    

次に、これが発生したら、他の例外と同様に単純に処理できます。

@Override
protected ResponseEntity handleNoHandlerFoundException(
  NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    String error = "No handler found for " + ex.getHttpMethod() + " " + ex.getRequestURL();

    ApiError apiError = new ApiError(HttpStatus.NOT_FOUND, ex.getLocalizedMessage(), error);
    return new ResponseEntity(apiError, new HttpHeaders(), apiError.getStatus());
}


以下に簡単なテストを示します。

@Test
public void whenNoHandlerForHttpRequest_thenNotFound() {
    Response response = givenAuth().delete(URL_PREFIX + "/api/xx");
    ApiError error = response.as(ApiError.class);

    assertEquals(HttpStatus.NOT_FOUND, error.getStatus());
    assertEquals(1, error.getErrors().size());
    assertTrue(error.getErrors().get(0).contains("No handler found"));
}

リクエスト全体を見てみましょう。

Request method:  DELETE
Request path:   http://localhost:8080/spring-security-rest/api/xx

そしてerror JSON response:

{
    "status":"NOT_FOUND",
    "message":"No handler found for DELETE /spring-security-rest/api/xx",
    "errors":[
        "No handler found for DELETE /spring-security-rest/api/xx"
    ]
}

5. HttpRequestMethodNotSupportedExceptionを処理する

次に、サポートされていないHTTPメソッドを使用してリクエストを送信したときに発生するもう1つの興味深い例外であるHttpRequestMethodNotSupportedExceptionを見てみましょう。

@Override
protected ResponseEntity handleHttpRequestMethodNotSupported(
  HttpRequestMethodNotSupportedException ex,
  HttpHeaders headers,
  HttpStatus status,
  WebRequest request) {
    StringBuilder builder = new StringBuilder();
    builder.append(ex.getMethod());
    builder.append(
      " method is not supported for this request. Supported methods are ");
    ex.getSupportedHttpMethods().forEach(t -> builder.append(t + " "));

    ApiError apiError = new ApiError(HttpStatus.METHOD_NOT_ALLOWED,
      ex.getLocalizedMessage(), builder.toString());
    return new ResponseEntity(
      apiError, new HttpHeaders(), apiError.getStatus());
}


この例外を再現する簡単なテストを次に示します。

@Test
public void whenHttpRequestMethodNotSupported_thenMethodNotAllowed() {
    Response response = givenAuth().delete(URL_PREFIX + "/api/foos/1");
    ApiError error = response.as(ApiError.class);

    assertEquals(HttpStatus.METHOD_NOT_ALLOWED, error.getStatus());
    assertEquals(1, error.getErrors().size());
    assertTrue(error.getErrors().get(0).contains("Supported methods are"));
}

そして、ここに完全なリクエストがあります:

Request method:  DELETE
Request path:   http://localhost:8080/spring-security-rest/api/foos/1

そしてthe error JSON response:

{
    "status":"METHOD_NOT_ALLOWED",
    "message":"Request method 'DELETE' not supported",
    "errors":[
        "DELETE method is not supported for this request. Supported methods are GET "
    ]
}

6. HttpMediaTypeNotSupportedExceptionを処理する

次に、クライアントがサポートされていないメディアタイプでリクエストを送信したときに発生するHttpMediaTypeNotSupportedExceptionを次のように処理しましょう。

@Override
protected ResponseEntity handleHttpMediaTypeNotSupported(
  HttpMediaTypeNotSupportedException ex,
  HttpHeaders headers,
  HttpStatus status,
  WebRequest request) {
    StringBuilder builder = new StringBuilder();
    builder.append(ex.getContentType());
    builder.append(" media type is not supported. Supported media types are ");
    ex.getSupportedMediaTypes().forEach(t -> builder.append(t + ", "));

    ApiError apiError = new ApiError(HttpStatus.UNSUPPORTED_MEDIA_TYPE,
      ex.getLocalizedMessage(), builder.substring(0, builder.length() - 2));
    return new ResponseEntity(
      apiError, new HttpHeaders(), apiError.getStatus());
}


この問題に遭遇した簡単なテストを次に示します。

@Test
public void whenSendInvalidHttpMediaType_thenUnsupportedMediaType() {
    Response response = givenAuth().body("").post(URL_PREFIX + "/api/foos");
    ApiError error = response.as(ApiError.class);

    assertEquals(HttpStatus.UNSUPPORTED_MEDIA_TYPE, error.getStatus());
    assertEquals(1, error.getErrors().size());
    assertTrue(error.getErrors().get(0).contains("media type is not supported"));
}

最後に、リクエストの例を次に示します。

Request method:  POST
Request path:   http://localhost:8080/spring-security-
Headers:    Content-Type=text/plain; charset=ISO-8859-1

そしてthe error JSON response:

{
    "status":"UNSUPPORTED_MEDIA_TYPE",
    "message":"Content type 'text/plain;charset=ISO-8859-1' not supported",
    "errors":["text/plain;charset=ISO-8859-1 media type is not supported.
       Supported media types are text/xml
       application/x-www-form-urlencoded
       application/*+xml
       application/json;charset=UTF-8
       application/*+json;charset=UTF-8 */"
    ]
}

7. デフォルトのハンドラ

最後に、フォールバックハンドラーを実装しましょう。これは、特定のハンドラーを持たない他のすべての例外を処理するキャッチオールタイプのロジックです。

@ExceptionHandler({ Exception.class })
public ResponseEntity handleAll(Exception ex, WebRequest request) {
    ApiError apiError = new ApiError(
      HttpStatus.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage(), "error occurred");
    return new ResponseEntity(
      apiError, new HttpHeaders(), apiError.getStatus());
}




8. 結論

Spring REST API用の適切で成熟したエラーハンドラーを構築するのは難しく、間違いなく反復的なプロセスです。 このチュートリアルが、APIのためにそれを行うための良い出発点であり、また、APIのクライアントがエラーを迅速かつ簡単に診断し、それらを通過するのを支援する方法の良いアンカーになることを願っています。

このチュートリアルのfull implementationは、the github projectにあります。これはEclipseベースのプロジェクトであるため、そのままインポートして実行するのは簡単です。