Created
December 11, 2021 16:24
-
-
Save philsch/0433a702383bb70dd6143f2bdc48c8c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { ApolloServer, gql } = require('apollo-server'); | |
const {GraphQLErrorTrackingExtension} = require('graphql-error-tracking-extension'); | |
const {ErrorReporting} = require('@google-cloud/error-reporting'); | |
const errorReporting = new ErrorReporting(); | |
/* | |
* ---------------------------------------- | |
* Let's define some custom errors | |
* ---------------------------------------- | |
*/ | |
class SomeError extends Error { | |
constructor(msg) { | |
super(msg); | |
this.name = 'Some Error'; | |
} | |
} | |
class SecretError extends Error { | |
constructor(msg) { | |
super(msg); | |
this.name = 'Secret Error'; | |
} | |
} | |
/* | |
* ---------------------------------------- | |
* The GraphQL Server | |
* ---------------------------------------- | |
*/ | |
const typeDefs = gql` | |
type Query { | |
# | |
# Some example endpoint to trigger Errors | |
# | |
triggerError(errorType: String): String | |
} | |
`; | |
const resolvers = { | |
Query: { | |
triggerError: (parent, args, context, info) => { | |
switch (args.errorType) { | |
case 'some': | |
throw new SomeError('Some error happened'); | |
case 'secret': | |
throw new SecretError('A secret error'); | |
default: | |
throw Error('Unknown error'); | |
} | |
} | |
} | |
} | |
const server = new ApolloServer({ | |
typeDefs, | |
resolvers, | |
extensions: [() => new GraphQLErrorTrackingExtension({ | |
revealErrorTypes: [SomeError], | |
onUnrevealedError: (err, originalError) => { | |
console.log(`onUnrevealedError called for ${err.name} (original error was "${err.originalError.name}")`); | |
if (originalError) { | |
errorReporting.report(err.originalError.stack); | |
} else { | |
errorReporting.report(err.stack); | |
} | |
} | |
})], | |
context: ({req}) => ({ | |
request: req | |
}) | |
}); | |
server.listen({port: 8080}).then(({ url }) => { | |
console.log(`🚀 Server ready at ${url}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment