我正在尝试使用Typescript来开发一个新的REST API。 我有一个看起来像这样的控制器。
export default class AuthController {
static async getRegisterController(
req: Request,
res: Response,
next: NextFunction,
): Promise<Response> {
const vendorData: RegisterInput = {
name: req.body.name,
email: req.body.email,
password: req.body.password,
contactNo: req.body.contactNo,
referralCode: req.body.referralCode,
};
const userWithEmail = await VendorData.getVendorWithEmail(vendorData.email);
if (userWithEmail) {
return next(new ConflictException('User with email already exists'));
}
const hashedPassword = await hashPassword(vendorData.password);
vendorData.password = hashedPassword;
const savedVendor = await VendorData.insertVendor(vendorData);
const successResult = Result.success(savedVendor);
return new ApiResponse(res, successResult).apiSuccess();
}
}
但是,我无法在此处返回next()
函数,因为返回类型与控制器的返回类型冲突。异步函数总是返回promise
,但next
函数返回类型为void
。但是,我确实需要下一个函数将我的错误传播到全局错误处理中间件以发送适当的响应。
编辑: 我只想在调用next(err);
后停止执行。只是return;
之后next(err)
就不起作用,因为return;
从异步函数返回Promise<undefined>
,而异步函数在这里也不起作用。
我现在找到的解决方案是让您的控制器返回Promise<Response | undefined>
.由于路由器不关心控制器的返回类型,因此这是可能的。