graphql-js中的graphql错误和状态消息 [英] graphql errors and status messages in graphql-js

查看:560
本文介绍了graphql-js中的graphql错误和状态消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从概念上讲,我迷上了graphsql(使用graphql-js).

假设API用户发送了一个查询,并且数据库服务器已关闭,我想将此信息作为

中的错误返回.

data { errors }

列表.

如何访问数据中的错误对象并在其中推送我自己的错误消息(例如,有关数据库服务器故障的消息)?

我想知道的下一件事是如何向数据对象添加附加消息对象.

假设用户已通过ID(例如特定帐户)请求了一个数据库项目,但该项目不存在.现在,我想返回这样的内容:

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

我该怎么做,我还必须将消息定义为一种类型吗?

解决方案

使errorsmessages字段出现在GraphQL响应的data属性内部的唯一方法是将它们包括在类型中GraphQL模式的系统,并向客户端明确要求它们.但是,如果您希望在每次请求时都返回一个自定义的errorsmessages字段,而不管客户端是否要求它们,都可以将它们包括在data属性之外.

例如,如果您使用的是express-graphql,它提供了扩展选项,允许您将多余的信息附加到每个响应有效负载上(

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

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!

这篇关于graphql-js中的graphql错误和状态消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆