如何使用 Apollo GraphQL 服务器仅捕获非 ApolloError 错误
How to Only Catch non-ApolloError Errors with Apollo GraphQL Server
我有一个 Apollo GraphQL 服务器,我只想报告内部服务器错误(而不是扩展 ApolloError
的错误,例如 AuthenticationError
、UserInputError
等)。
这是我编写的捕获内部服务器错误并报告它们的插件:
const errorReportingPlugin = {
requestDidStart(_) {
return {
didEncounterErrors(ctx) {
// If we couldn't parse the operation, don't do anything
if (!ctx.operation) return
for (const err of ctx.errors) {
// Don't report errors extending ApolloError like AuthenticationError, UserInputError, etc.
if (err instanceof ApolloError) {
continue
}
// report error here...
}
}
}
}
}
但是 err instanceof ApolloError
returns false
当我抛出 AuthenticationError
时,它扩展了 ApolloError
.
所以我尝试通过打印构造函数名称来检查 err
的 class
,我得到了 GraphQLError
。
console.log(err.constructor.name)
有谁知道如何避免报告扩展 ApolloError
的所有错误?
解决方案是检查 err.originalError
(不是 err
)是否是 ApolloError
的实例,如下所示:
if (err.originalError instanceof ApolloError) {
// don't report error since it is a user facing error like AuthenticationError, UserInputError, etc.
}
感谢@xadm
我有一个 Apollo GraphQL 服务器,我只想报告内部服务器错误(而不是扩展 ApolloError
的错误,例如 AuthenticationError
、UserInputError
等)。
这是我编写的捕获内部服务器错误并报告它们的插件:
const errorReportingPlugin = {
requestDidStart(_) {
return {
didEncounterErrors(ctx) {
// If we couldn't parse the operation, don't do anything
if (!ctx.operation) return
for (const err of ctx.errors) {
// Don't report errors extending ApolloError like AuthenticationError, UserInputError, etc.
if (err instanceof ApolloError) {
continue
}
// report error here...
}
}
}
}
}
但是 err instanceof ApolloError
returns false
当我抛出 AuthenticationError
时,它扩展了 ApolloError
.
所以我尝试通过打印构造函数名称来检查 err
的 class
,我得到了 GraphQLError
。
console.log(err.constructor.name)
有谁知道如何避免报告扩展 ApolloError
的所有错误?
解决方案是检查 err.originalError
(不是 err
)是否是 ApolloError
的实例,如下所示:
if (err.originalError instanceof ApolloError) {
// don't report error since it is a user facing error like AuthenticationError, UserInputError, etc.
}
感谢@xadm