I'm facing a challenge with writing custom HTTP responses from NestJS exception filters. Currently, I am using the Nest Fastify framework instead of Express. I have created custom exception filters to handle UserNotFoundException in the following manner:
@Catch(UserNotFoundException)
export class UserNotFoundExceptionFilter implements ExceptionFilter {
catch(exception: UserNotFoundException, host: ArgumentsHost) {
const errorResponse = new ErrorResponse<string[]>();
const response = host.switchToHttp().getResponse();
errorResponse.message = 'unauthorized exception'
errorResponse.errors = [
'invalid username or password'
];
response.status(401).json(errorResponse)
}
}
However, I keep encountering the error message "response.status(...).json() is not a function."
[Nest] 5400 - 05/17/2020, 00:27:26 [ExceptionsHandler] response.status(...).json is not a function +82263ms
TypeError: response.status(...).json is not a function
I understand that I need to specify the type of response writer (e.g., Response from Express).
To address this issue, I attempted importing the Response object from Express and updating the type of the response variable as follows:
import {Response} from 'express';
const response = host.switchToHttp().getResponse<Response>();
After making these changes, everything worked smoothly. However, I prefer not to introduce Express elements into my NestJS Fastify application. Is there an alternative class that can replace the Express Response object? Any suggestions for a more elegant solution would be greatly appreciated.
Thank you all.