首页 > 解决方案 > graphql 错误消息获取完整的 http 响应

问题描述

我正在使用apollo-client. 发生错误时,HTTP 响应如下所示。

{
  "data": {
    "loginEmail": null
  },
  "errors": [
    {
      "message": "VALIDATION_FAILED",
      "locations": [
        {
          "line": 43,
          "column": 3
        }
      ],
      "path": [
        "loginEmail"
      ],
      "errors": [
        {
          "model": "user",
          "field": "password",
          "code": "INVALID",
          "extra": null
        }
      ]
    }
  ]
}

上面的消息是用 Chrome devtools 捕获的。但是如何捕捉这个完整的响应错误消息apollo-client呢?

使用以下代码,我得到的只是GraphQL error: VALIDATION_FAILED

async function loginEmail(email, password) {
  // ...
  try {
    const res = await gqclient.mutate({ // gqclient comes from `new ApolloClient({...})`
      mutation,
      variables: { 
        "email": email,
        "password": password
      }
    })
    return res
  } catch (err) {
    logger.debug(err)   // all I got is `GraphQL error: VALIDATION_FAILED`
    return err
  }
}

有任何想法吗?

谢谢!


- - - - 更新 - - - -

感谢@cgcgbcbc 的提醒!我的winston配置错误。

但我不知道为什么?

这没关系(logger.info(err)可以获得完整的响应消息):

const { createLogger, format, transports } = require('winston')

const logger = createLogger({
  level: 'debug',
  format: format.combine(
    format.timestamp({format: 'YYYY-MM-DDTHH:mm:ss'}),
    format.json()
  ),
  transports: [new transports.File({filename: 'logs/new_combined.log'})]
})

// output
// {
//    "graphQLErrors":[
//       {
//          "message":"VALIDATION_FAILED",
//          "locations":[
//             {
//                "line":2,
//                "column":3
//             }
//          ],
//          "path":[
//             "loginEmail"
//          ],
//          "errors":[
//             {
//                "model":"user",
//                "field":"password",
//                "code":"INVALID",
//                "extra":null
//             }
//          ]
//       }
//    ],
//    "networkError":null,
//    "message":"GraphQL error: VALIDATION_FAILED",
//    "level":"info",
//    "timestamp":"2019-02-26T15:26:19"
// }

这是不行的:

const { createLogger, format, transports } = require('winston')

const logger = createLogger({
  level: 'debug',
  format: format.combine(
    format.timestamp({format: 'YYYY-MM-DDTHH:mm:ss'}),
    format.printf(info => {
      return JSON.stringify({
        timestamp: info.timestamp, 
        level: info.level, 
        message: info.message})
    })
  ),
  transports: [new transports.File({filename: 'logs/new_combined.log'})]
})

// output
// {
//    "timestamp":"2019-02-26T15:36:32",
//    "level":"info",
//    "message":"GraphQL error: VALIDATION_FAILED"
// }

标签: node.jsapollo-clientwinston

解决方案


推荐阅读