gpt4 book ai didi

node.js - 处理ExpressJS中混合的同步和异步错误的最佳方法

转载 作者:行者123 更新时间:2023-12-03 08:46:08 24 4
gpt4 key购买 nike

使用NodeJS 10.13.0,ExpressJS 4.16.4 ...
得到了一个处理如下路由的 Controller :

import { Request, Response, NextFunction } from 'express';
import braintree from 'braintree';
import config from '../../server.config';

export function index(req: Request, res: Response, next: NextFunction): void {
if(!config.braintree) throw new Error('Braintree configuration missing.');
const gateway: any = braintree.connect(config.braintree); // synchronous
return gateway.clientToken.generate({})
.then(response => res.send(response.clientToken))
.catch(next) // operational error unless config.braintree was changed
}

阅读 ExpressJS docs on error handling,我想知道我是否遵循最佳实践-为同步部分抛出错误,并将错误传递给异步部分的catch中的next()。

有什么改进建议吗?

最佳答案

考虑到正在使用promise,可以使用async函数一致地处理同步和异步错误:

export async function index(req: Request, res: Response, next: NextFunction) {
try {
if(!config.braintree)
throw new Error('Braintree configuration missing.');

const gateway: any = braintree.connect(config.braintree);
const response = await gateway.clientToken.generate({})
res.send(response.clientToken);
} catch (err) {
next(err);
}
}

由于Express不支持promise,因此 async函数主体应使用 try..catch包装。考虑到 try..catch对于所有 async中间件功能都是通用的,因此可以将其移到帮助程序中:
const asyncMiddleware = (middleware: RequestHandler) => async (req: Request, res: Response, next: NextFunction) => {
try {
await middleware(req, res, next);
} catch (err) {
next(err)
}
};

用法如下:
export const index = asyncMiddleware(async (...) => {...});

关于node.js - 处理ExpressJS中混合的同步和异步错误的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53542721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com