graphql errors and status messages in graphql-js

南楼画角 提交于 2020-01-25 22:09:08

问题


I'm conceptually stuck with graphsql (using graphql-js).

Lets's say the API user sends a query and the database-server is down and I'd like to return this information as an error in the in the

data { errors }

list.

How can i access the errors object in data and push my own error messages (e.g. about the database-server outage) there?

Next thing I am wondering about is how to add an addition messages object to the data object.

Let's say The user has requested a database item by id (e.g. a particular account) and that item does not exist. Now, I'd like to return something like this:

{
    data: {
        messages: [{status: "failure", message: "This account does not exist"}]
    }
}

How would I do that and would I have to define the messages also as a type?


回答1:


The only way to get errors and messages fields to appear inside of the data property of the GraphQL response is to include them in the type system of your GraphQL schema and to explicitly ask for them from the client. However, if you want to have a custom errors and messages field that is returned on every request regardless of whether the client asked for them or not you can include them outside the data property.

For example, if you are using express-graphql, it provides an extensions option that allows you attach any excess information to every response payload (https://github.com/graphql/express-graphql/blob/c92cfad64f4b18abce3cdeca36bb8553dd020773/src/index.js#L95)

If you are not using express-graphql, you can look at it as an example of how you can include your own metadata in each response. express-graphql is a pretty simple wrapper and you can always just write your own data into the response. For example, this is the line where express-graphql attaches errors (https://github.com/graphql/express-graphql/blob/c92cfad64f4b18abce3cdeca36bb8553dd020773/src/index.js#L309). You could do the same but under a different key.

Best of luck!




回答2:


One way of having errors and messages as part of query result is to include them as fields to your GraphQL object type(s).

For example, you have a GraphQL object type Item with fields id, name, errors and messages. When the database server is down, only errors field of item instance is populated. When an item with the given ID is unavailable, messages field is populated. When the item is available, name field is set.



来源:https://stackoverflow.com/questions/41720509/graphql-errors-and-status-messages-in-graphql-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!