-
-
Save autaut03/15af00e63cb41cad77e35c7cab1d1330 to your computer and use it in GitHub Desktop.
NestJS many app providers fail example
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
@Module({ | |
providers: [ | |
Logger, | |
{ | |
provide: APP_FILTER, | |
useClass: InternalServerErrorFilter // if this comes first, it will never work | |
}, { | |
provide: APP_FILTER, | |
useClass: ForbiddenFilter // the one that comes last always works | |
} | |
] | |
}) | |
export class AppModule {} |
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
@Catch(ForbiddenException) | |
export class ForbiddenFilter implements ExceptionFilter { | |
catch(exception: ForbiddenException, host: ArgumentsHost) { | |
response(host) | |
.error( | |
'forbidden', | |
'Access denied.', | |
HttpStatus.FORBIDDEN | |
); | |
} | |
} |
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
@Catch() | |
export class InternalServerErrorFilter implements ExceptionFilter { | |
constructor( | |
private readonly logger: Logger | |
) {} | |
catch(exception: Error, host: ArgumentsHost) { | |
this.logger.error(exception.message, exception.stack); | |
response(host) | |
.error( | |
'internal_server_error', | |
'Whoops. Something went wrong.', | |
HttpStatus.INTERNAL_SERVER_ERROR | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment