티스토리 뷰

graphql에서 에러발생시 기본적으로 제공하는 정보외에 원하는 정보를 더 추가하고 싶다면,
graphql-java library에 있는 GraphQLError interface 사용하여
exception 클래스를 구현해야 한다.

GraphQLError interface에는 abstract method가 아래와 같이 3개 있다.

List getLocations()
ErrorClassification getErrorType()
String getMessage()


getLocations()와 getErrorType()의 경우 {return null;} 로 구현을 하면 된다.
(default error handler에서 location과 errorytype의 값을 가져올 때 다른 값을 사용하기 때문에 의미 없다)
getMessage()의 경우는 RuntimeException class에서 override하기 때문에 구현하지 않아도 된다.

실제적으로 override 해서 사용해야 하는 부분은 getExtensions 메소드이다.

Map<String, Object> getExtensions()


graphql의 경우 error가 발생하면 response에 'errors' 필드에서 error에 대한 정보를 담아주고 있는데
'errors'에서 사용자가 원하는 정보를 추가할 수 있는 필드가 'extensions'이다.

아래와 같이 구현을 하게 되면

@Override
public Map<String, Object> getExtensions() {
    Map<String, Object> customAttributes = new LinkedHashMap<>();
    customAttributes.put("errorCode", "Custom Test Error Code");
    customAttributes.put("errorMessage", "This is Custom Error Message");
    return customAttributes;
}


errors.extensions의 값이 아래와 같이 나오는 것을 확인할 수 있다.

{
  "errors": [
    {
      "message": .......,
      "locations": [
        {
          "line": ...,
          "column": ....
        }
      ],
      "path": [
        .....
      ],
      "extensions": {
        "errorCode": "Custom Test Error Code",
        "errorMessage": "This is Custom Error Message",
        "classification": "DataFetchingException"
      }
    }
  ],
  "data": null
}


예제 코드는 다음과 같다.

import graphql.ErrorType;
import graphql.GraphQLError;
import graphql.language.SourceLocation;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class CustomGraphQLException extends RuntimeException implements GraphQLError {
    private final int errorCode;

    public CustomGraphQLException(int errorCode, String errorMessage) {
        super(errorMessage);
        this.errorCode = errorCode;
        this.errorType = errorType;
    }

    @Override
    public Map<String, Object> getExtensions() {
        Map<String, Object> customAttributes = new LinkedHashMap<>();
        customAttributes.put("errorCode", this.errorCode);
        customAttributes.put("errorMessage", this.getMessage());
        return customAttributes;
    }

    @Override
    public List getLocations() {
        return null;
    }

    @Override
    public ErrorType getErrorType() {
        return null;
    }
}




너무 당연하지만 error 호출은 아래와 같이 하면 된다.

throw new CustomGraphQLException(XXXX, "XXXXXXXX")
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함