Last active
October 5, 2022 01:02
-
-
Save MrTin/7c2d1a508ff0cb934df480689e950d72 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
// https://www.apollographql.com/docs/apollo-server/data/errors/#unauthenticated | |
// Using types and unions | |
// https://blog.logrocket.com/handling-graphql-errors-like-a-champ-with-unions-and-interfaces/ | |
// Wrap mutation with result{user, errors} | |
// https://stackoverflow.com/a/55532706 | |
// UserInputError | |
// ValidationError | |
// ForbiddenError | |
// #1 | |
throw new UserInputError('User with this slug already exists!') | |
// #2 | |
throw new ApolloError('My error message', 'MY_ERROR_CODE', myCustomExtensions); | |
// #3 | |
import { ApolloError } from 'apollo-server-errors'; | |
export class MyError extends ApolloError { | |
constructor(message: string) { | |
super(message, 'MY_ERROR_CODE'); | |
Object.defineProperty(this, 'name', { value: 'MyError' }); | |
} | |
} | |
throw new MyError('My error message') | |
// Pipes #1 | |
@UsePipes(new JoiValidationPipe(createCatSchema)) | |
async create(@Body() createCatDto: CreateCatDto) { | |
this.catsService.create(createCatDto); | |
} | |
// Pipes #2 | |
@Mutation(returns => Group) | |
async createGroup( | |
@Args('group', new ValidationPipe()) | |
input: CreateGroupInput, | |
) | |
// catch-all setup for ApolloServer | |
formatError(err) { | |
if (err.originalError instanceof AuthenticationError) { | |
return new Error('Different authentication error message!'); | |
} | |
}, | |
// ONLY CATCH SPECIFIC ERRORS AND RE-THROW OTHERS | |
try { | |
myroutine(); // There's a couple of errors thrown here | |
} catch (e) { | |
if (e instanceof TypeError) { | |
// A TypeError | |
} else if (e instanceof RangeError) { | |
// Handle the RangeError | |
} else if (e instanceof EvalError) { | |
// you guessed it: EvalError | |
} else if (typeof e === "string") { | |
// The error is a string | |
} else if (axios.isAxiosError(e)) { | |
// axios does an error check for us! | |
} else { | |
// everything else | |
logMyErrors(e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment