【问题标题】:React-Apollo error only shows status code 500React-Apollo 错误只显示状态码 500
【发布时间】:2019-08-13 10:14:11
【问题描述】:

我想知道如何使用 react-apollo 在前端访问我的抛出错误?

我用于获取单个客户的简单解析器是这样的,其中args._id 是客户 ID。现在如果 id 无效,react-apollo 只会抛出 500 错误。

错误!网络错误:响应不成功:收到状态码 500

   customer: async (args, req) => {
        const validateId = (id) => {
            return mongoose.Types.ObjectId.isValid(id)
        }
        if(args._id && validateId(args._id)){
            try { 

                const customer = await Customer
                    .findById(args._id)

                return transformCustomer(customer)
            }
            catch (err) {
                throw err
            }
        }
        else {
            throw new Error("error")
        }
    },

我尝试使用 errorPolicy="all" 并访问 error.graphQLErrors,但这不起作用,因为它会引发 500 错误。

无法读取未定义的属性“graphQLErrors”

【问题讨论】:

    标签: reactjs graphql apollo react-apollo


    【解决方案1】:

    编辑(除了包装在 try/catch 中)- 也许您应该在向服务器发送请求之前检查 _id 是否有效:

    customer: async (args, req) => {
        // do some validation on _id
        if (args._id && isValid(args._id) ) {
            try {
                const customer = await Customer.findById(args._id)
            } catch (e) {
              // handle server error
            }
        } else {
           // handle invalid _id here
        }
    

    【讨论】:

    • 我需要向服务器检查_id是否有效?所以我认为if(!customer)如果无效则抛出错误会起作用吗?
    • no - 因为当您检查 if(!customer 时已经抛出错误 - 这就是为什么您需要将其包装在 try/catch 中的原因。如果您需要将其发送到服务器进行检查,请忽略上述内容..
    • 但是如果每次都抛出 500 服务器错误,并且 Apollo 客户端总是呈现“错误!网络错误:响应不成功:收到状态码 500”时发生这种情况?我不明白。
    【解决方案2】:

    要捕获 apollo 引发的错误,您需要将执行查询的调用包装到 try-catch

    在您的示例中,这可能是:

    try {
        const customer = await Customer.findById(args._id);
    } catch(err) {
        // handle the error
    }
    

    但是500 始终是一个编程错误,应该在服务器上修复。在使用查询中传递的参数之前,您的服务器似乎没有进行所需的验证。

    【讨论】:

    • 您如何建议我检查该 ID 是否为现有文档?我正在使用 Mongoose,在使用 Graphiql 时,我收到错误消息。但是在使用 Apollo Client 时,我只收到网络错误。
    猜你喜欢
    • 2014-11-18
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 2019-05-11
    • 2019-11-27
    • 2021-07-25
    相关资源
    最近更新 更多