我创建了一个nodejs / express api,它是另一个api的包装。
我正在使用try and catch进行异步调用。我想知道内部异步调用是否捕获到错误,外部异步调用会捕获此错误。
transaction.controller是我的api,它将transaction.repository调用到外部api。函数getTransactionResult
在catch部分抛出错误。但是,这不会循环回到我的show
函数的catch部分。
router.ts
this.router.get('/:id', this.controller.show.bind(this.controller));
transaction.controller.ts
public async show(req: Request, res: Response): Promise<any> {
const params = req.params;
const token = req.headers.token;
let transaction;
try {
transaction = await this.transactionRepo.getTransactionResult(params.id, token);
console.log("instead carries on here"); // 2
if (transaction.success === false) {
return res.status(404).json({
success: false,
status: 404,
data: transaction,
message: "Failed to retrieve transaction result"
});
}
return res.status(200).json({
success: true,
status: 200,
data: transaction,
message: "Successfully retrieved transaction result"
});
} catch (err) {
//console.log("Does not call this");
return res.status(500).json({
success: false,
status: 400,
data: err,
message: "The server threw an unexpected error",
});
}
transaction.repository.ts
public async getTransactionResult(transactionId: string, token: string) {
const url = this.config.api_url + "/api/transactions/" + transactionId + "/summary";
const options = {
uri: url,
headers: {
'token': token
},
body: {
},
json: true,
resolveWithFullResponse: true
}
let result;
try {
result = await request.get(options);
if (result.statusCode !== 200) {
return { "success": false, data: result }
}
return { "success": true, data: result }
} catch (err) {
console.log("CAUGHT ERROR"); // 1
return err;
}
}
答案 0 :(得分:2)
您需要重新throw
错误不 return
。
通过执行return err
,您resolving是Promise
,这意味着异步操作成功。因此,为什么您在try-catch
中的transaction.controller.ts
却什么都没捉住。
要么:
不要抓住错误并让它冒出来
重新throw
错误