Modify unauthorized exception
Closed this issue ยท 5 comments
I'm submitting a...
[ ] Regression
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Expected behavior
It would be interesting to add documentation/feature to be able to modify the Unauthorized exception when jwt is invalid, has expired...
+1
I would also like to send a custom exception in case of expired/invalid JWT. Just sending an Unauthorised exception is not enough to know whether is because of the token or other reason.
Just wrap method call with try..catch
and return an exception tailored to your app's requirements.
@kamilmysliwiec
What method exactly? In case of an expired/invalid JWT token, the controller's method won't be called, so where exactly should I put try...catch
? Sorry if it seems like a dumb question. Maybe you could provide a basic example like in the documentation, it would be appreciated.
@JaumeS4 @popemann Possible solution is to use exception filter and substitute your custom exception whenever the UnauthorizedException
is fired.
- Create the filter:
unauthorized-exception.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, UnauthorizedException } from '@nestjs/common';
import { Response } from 'express';
import { UnauthorizedException as MyUnauthorizedException } from '../exception/exception';
@Catch(UnauthorizedException)
export class UnauthorizedExceptionFilter implements ExceptionFilter {
catch(exception: UnauthorizedException, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
let status = exception.getStatus();
response
.status(status)
.json({
timestamp: new Date().toISOString(),
error: new MyUnauthorizedException()
});
}
}
- Enable the filter:
main.ts
app.useGlobalFilters(new UnauthorizedExceptionFilter());
But yea, cleaner way would be to make it possible to override passport fail
callback or whatever.