ExpediaGroup / graphql-kotlin

Libraries for running GraphQL in Kotlin

Home Page:https://opensource.expediagroup.com/graphql-kotlin/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Return custom HTTP status codes

rb090 opened this issue Β· comments

commented

Hi πŸ‘‹,

I start using your library to provide a GraphQL API endpoint. I am working on the error handling right now. I read your documentation Exceptions and Partial Data regarding this. Returning errors like described there works very well.

I am coming from the REST world and there I am used to return corresponding HTTP Status codes in case that sth went wrong. So fe. when my code throws an IllegalArgumentException somewhere, I like to return fe. HTTP status code 400 (bad request) and an error json:

{
  "title": "Sth went wrong",
  "message": "Some message here explaining more"
}

Can you please tell me whether sth similar is possible in graphql and with your library?

Probably not with DataFetcherResult because there, HTTP status code is always 200.

Can I throw somehow a custom graphql exception which produces a similar result like I would like it to have?

Thanks in regards for any suggestion on this. Please be patient with me, it is my 1st GQL server project πŸ™ˆ

commented

So to maybe wireframe my question a bit in code, if I have a mutation like this:

class MyMutation : Mutation {

    fun sampleMutationDoingSth(user: User): ReturnObject? {

        val result = methodCallWhichCanThrow(user: user)

        return ReturnObject(userName=result.name)
    }
}

It would be nice if in case that methodCallWhichCanThrow throws an exception like fe. an IllegalStateException the server responds with an HTTP Status code different than 200. Fe. HTTP Status code 500.

ATM in case of an exception the server returns this and HTTP status code 200:

{
    "data": {
        "sampleMutationDoingSth": null
    },
    "errors": [
        {
            "message": "Exception while fetching data (/sampleMutationDoingSth) : <EXCEPTION message here>",
            "locations": [
                {
                    "line": 2,
                    "column": 5
                }
            ],
            "path": [
                "sampleMutationDoingSth"
            ]
        }
    ]
}

I am really thankful for any hint on this. I already read that it is not usual that graphql server return "error http status codes" in case of errors like fe. REST APIs would do. But I also saw Rust GQL server doing this fe.

And you also do this in case that I try to read out headers within my mutation by using DataFetchingEnvironment. And the header I expect is not there. Then GQL server answers me with HTTP Status 400 which is exactly the right thing.

And also what I would like the server to do in case an exception is thrown within my code.