首页 文章

在Vue.js中向用户显示Apollo变异错误?

提问于
浏览
1

我正在使用带有Vue-ApolloVue.js并启动用户突变来登录用户 . 我正在使用graph.cool服务 .

我有一个请求管道功能设置来捕获一些错误,如无效的电子邮件 .

当使用错误/无效输入发出请求时,我的错误 catch() 会触发(如预期的那样),并且在网络选项卡中,我可以看到自定义错误消息的JSON . 但是如果从graph.cool触发错误,如何从catch中访问这些错误/响应?

Example:

signin () {
  const email = this.email
  const password = this.password

  this.$apollo.mutate({
    mutation: signinMutation,
    variables: {
      email,
      password
    }
  })
  .then((data) => {
    // This never fires on an error, so I can't 
    // show the user the errors in the network repsonse.
    console.log(data) 
  })
  .catch((error) => {
    // Error in this part fires in the console 
    // but I'm unable to show the JSON response 
    // errors because the 'then()' above doesn't execute.
    console.error(error)
  })
}

我为无法识别的用户收到以下错误:

错误:GraphQL错误:没有用户在新的ApolloError(eval at(app.js:956),:34:28)在eval(eval at(app.js:1353),:139:33)处找到该信息

知道如何在 catch() 中显示响应中的错误吗?

我可以在网络选项卡上的字幕中看到我想要向用户显示的错误:

enter image description here

......但我无法弄明白该怎么做 .

任何帮助非常感谢!谢谢 .

2 回答

  • 2

    所以,看起来好像我是通过咆哮错误的树来处理错误的方式 .

    答案的关键是检查 .catch()console.dir(error) 的错误 . 这揭示了一些有用的关键......即:

    error.graphQLErrors[0]
    

    总而言之,更正后的代码如下所示:

    signin () {
      const email = this.email
      const password = this.password
    
      this.$apollo.mutate({
        mutation: signinMutation,
        variables: {
          email,
          password
        }
      })
      .then(data => {
        console.log(data)
      })
      .catch(error => {
        console.log(graphQLErrorMessages(error))
      })
    }
    

    graphQLErrorMessages() 函数是我写的一个帮助器,所以我可以在其他 .catch() 块中重用它:

    function graphQLErrorMessages (errorsFromCatch) {
      const errors = errorsFromCatch.graphQLErrors[0]
      const messages = []
    
      if (errors.hasOwnProperty('functionError')) {
        const customErrors = JSON.parse(errors.functionError)
        messages.push(...customErrors.errors)
      } else {
        messages.push(errors.message)
      }
    
      return messages
    }
    

    它返回一组错误消息(这是我需要的)但你可以按照你喜欢的方式格式化它 .

    它的逻辑可能有点具体(我不太确定),但我希望这最终会帮助某人也陷入类似的境地!

  • 0

    我可能会误解你的问题,所以请注释并纠正我,如果我,但看起来你可能遇到的问题比使用Vue或GraphQL更多 .

    就像在 try...catch 语句中一样,一旦发现错误,程序将继续执行,除非您重新抛出错误 . 例如:

    This Catches

    try { 
      codeThatThrowsAnError();
    } catch(e) {
      // Do Nothing
    }
    

    This re-throws

    try { 
      codeThatThrowsAnError();
    } catch(e) {
      throw new Error("Err 135: I failed")
    }
    

    同样地,在Promise的土地上,你可以捕捉错误并像你的例子一样移动,或者你可以重新投掷 . 您可能缺少的是从catch语句返回的任何内容都将在下一个 then 中使用 . 例如:

    somethingReturningAFailedPromise()
      .then(doWork)
      .catch((err) => {
        return "I'm a New Value"
      })
      .then(console.log)
    
    //=> "I'm a New Value"
    

    听起来像你需要的是一个数据功能,它更能恢复故障,如下所示:

    const getUserProfile = (id) => {
      return fetchUserData(id)
        .catch((err) => {
          logError(err);
          return {};
        })
    }
    

相关问题