riz*_*sky 2 javascript typescript nestjs fastify nestjs-config
我在从 Nestjs 异常过滤器编写自定义 http 响应时遇到问题
我正在使用 Nest Fastify 过滤器(不是 Express)
我正在创建捕获 UserNotFoundException 的自定义异常过滤器,如下所示:
@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 pass'
];
response.status(401).json(errorResponse)
}
}
Run Code Online (Sandbox Code Playgroud)
我不断收到response.status(...).json() 不是函数。
[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
Run Code Online (Sandbox Code Playgroud)
我知道我必须向某种类型的响应编写者指定该响应的类型(例如:来自快递的响应)。
我尝试从express导入该 Response对象,并将响应变量的类型更新为Response(express),如下所示:
import {Response} from 'express';
Run Code Online (Sandbox Code Playgroud)
const response = host.switchToHttp().getResponse<Response>();
Run Code Online (Sandbox Code Playgroud)
一切都进展顺利。
但我不想在我的应用程序中添加一些快速的东西,我只想使用nestjs fastify。你们知道有什么类可以代替express中的这个Response对象吗?或者如果你有另一种更聪明的方法来解决这个问题,它也会有帮助
谢谢大家
如果您正在使用,Fastify则需要使用FastifyReply<ServerResponse>来自的类型fastify和http包。Fastify 本身没有json回复对象的方法,但它有一个.send()方法,JSON.stringify()如果给定一个对象,它就会返回一个对象。
虽然如果您使用来自 的对象,项目可能会构建,但您可能会收到有关 的运行时错误。下面应该可以正常工作Responseexpressresponse.status().json is not a function
import { FastifyReply } from 'fastify';
@Catch(UserNotFoundException)
export class UserNotFoundExceptionFilter implements ExceptionFilter {
catch(exception: UserNotFoundException, host: ArgumentsHost) {
const errorResponse = new ErrorResponse<string[]>();
const response = host.switchToHttp().getResponse<FastifyReply<ServerResponse>>();
errorResponse.message = 'unauthorized exception'
errorResponse.errors = [
'invalid username or pass'
];
response.status(401).send(errorResponse)
}
}
Run Code Online (Sandbox Code Playgroud)
总体而言,Nest 是Express 和 Fastify 的包装器,并且在讨论库特定选项(例如请求和响应)时,大多数文档都与 Express 相关。当涉及到库特定方法时,您应该参考Fastify 的文档。