-
Notifications
You must be signed in to change notification settings - Fork 382
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(@nestjs/graphql): base exception filter for apollo exceptions
Closes #1053
- Loading branch information
Showing
4 changed files
with
57 additions
and
13 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import { Catch, ArgumentsHost, HttpException } from '@nestjs/common'; | ||
import { BaseExceptionFilter } from '@nestjs/core'; | ||
import { | ||
ApolloError, | ||
AuthenticationError, | ||
ForbiddenError, | ||
} from 'apollo-server-errors'; | ||
import { GqlContextType } from './services'; | ||
|
||
const apolloPredefinedExceptions: Record<number, typeof ApolloError> = { | ||
401: AuthenticationError, | ||
403: ForbiddenError, | ||
}; | ||
|
||
@Catch(HttpException) | ||
export class GraphQLBaseExceptionFilter extends BaseExceptionFilter { | ||
catch(exception: HttpException, host: ArgumentsHost) { | ||
if (host.getType<GqlContextType>() !== 'graphql') { | ||
return null; | ||
} | ||
|
||
let error: ApolloError; | ||
if (exception.getStatus() in apolloPredefinedExceptions) { | ||
error = new apolloPredefinedExceptions[exception.getStatus()]( | ||
exception.message, | ||
); | ||
} else { | ||
error = new ApolloError( | ||
exception.message, | ||
exception.getStatus().toString(), | ||
); | ||
} | ||
|
||
error.stack = exception.stack; | ||
error.extensions['response'] = exception.getResponse(); | ||
|
||
throw error; | ||
} | ||
} |
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
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
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