Apollo Server v4 Error Handling

Hey folks. I’m upgrading our Node/Next ApolloServer from v3 to v4. I see formatError has changed slightly. Reading Error Handling - Apollo GraphQL Docs, it suggests that it should always at least be the original error thrown, if not wrapped in GraphQLError. And below, the example predicates handling based on the error message rather than the error class.

The type of the second parameter is unknown in TypeScript. Why? Is there any case where it wouldn’t be GraphQLError | Error?

My intent was effectively to do something like the following.

// custom error
class InvalidInputError extends UserFacingError {}
...
// resolver
throw new InvalidInputError("..."); 

// formatError
if (error.originalError) {
  if (error.originalError instanceof UserFacingError) {
    return formattedError;
  }
} else {
  log.error(error);
  // return a 
}

Similarly, if I directly log the second parameter, the outputted json doesn’t contain originalError as a field. Is that intended?

1 Like

I would also like an answer to this. In JavaScript you can throw anything (which is maybe why it is unknown), but since everything gets wrapped by a GraphQLError with Apollo, I’m not sure why we can’t assume it is a GraphQLError.

It makes no sense to me why the error type for formatError is unknown, but it is of type GraphQLError for the didEncounterErrors plugin, which gets called before formatError.