我在编写来自 nestjs 异常过滤器的自定义 http 响应时遇到问题
我用的是nest fastify one(不是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)
}
}
我不断收到 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
我知道我必须指定 对某种类型的响应作者的响应类型(例如:来自 express 的响应)。
我尝试从 express 导入 Response 对象,并将 response 变量的类型更新为 Response(express),如下所示:
import {Response} from 'express';
const response = host.switchToHttp().getResponse<Response>();
一切顺利。
但我不想在我的应用程序中添加一些表达的东西,我只想使用 nestjs fastify。 你们知道有什么类可以从 express 中替换这个 Response 对象吗? 或者,如果您有另一种更聪明的方法来解决这个问题,它也会有所帮助
谢谢大家
最佳答案
如果您使用 Fastify
你需要使用 FastifyReply<ServerResponse>
从 fastify
输入和 http
包裹。 Fastify 本身没有 json
回复对象上的方法,但它确实有一个 .send()
将 JSON.stringify()
的方法一个对象,如果给它一个对象。
虽然如果您使用 Response
项目可能构建来自 express
的对象,您可能会收到关于 response.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)
}
}
总的来说,Nest 是 Express 和 Fastify 的包装器,在谈论库特定选项(如请求和响应)时,大多数文档都与 Express 相关。您应该引用 Fastify's documentation当涉及到特定于图书馆的方法时。
https://stackoverflow.com/questions/61841366/
相关文章:
swiftui - 我怎样才能在 SwiftUI 中实现类似于 radiogroup 的一种可能选择
ios - SecurityApplicationGroupIdentifier 的应用组返回 ni
typescript - 如何使用可选的唯一字符串定义数组 typescript 接口(interf
php - 如何解决 "The process has been signaled with sig
forms - 如何判断表单字段在 vue.js 中是否无效
scala - 通过方法类型参数分配给类型成员的值打破了类型等价
google-app-engine - gcloud app deploy - 更新服务默认值失败,
python - 将 Selenium 与 PyCharm CE 一起使用时的弃用问题