javascript - 如何使用 NestJS 的 httpService 捕获 3rd 方 api 错误响应?
问题描述
假设我像这样使用 httpService 发出请求
const response = await this.httpService
.request({
url: 'https://example.com/data',
method: 'POST',
})
.toPromise()
.catch(error => console.log(error))
假设 example.com/data api 发送类似“Cannot send data without specified user id”之类的消息。关于这个请求(如果我通过 curl 提出这个请求)
现在,如果我在上面的代码块中使用 httpService,我会得到这个模棱两可的消息:
Error: Request failed with status code 400 at createError (/workspace/node_modules/axios/lib/core/createError.js:16:15) at settle (/workspace/node_modules/axios/lib/core/settle.js:17:12) at IncomingMessage.handleStreamEnd (/workspace/node_modules/axios/lib/adapters/http.js:236:11) at IncomingMessage.emit (events.js:203:15) at endReadableNT (_stream_readable.js:1145:12) at process._tickCallback (internal/process/next_tick.js:63:19)"
但是如果我这样写 catch 语句
.catch(error => {
const errorLog = _.pick(error.response, [
'status',
'statusText',
'data',
]);
this.logger.error(
util.inspect(
{
...errorLog,
user: { id: user.id },
},
{ showHidden: false, depth: null },
),
);
throw new InternalServerErrorException();
});
我将在我的日志中获得第 3 方 api 响应“如果不指定用户 ID,就无法发送数据。”
那么,有没有办法让 httpService 默认以这种方式运行?像拦截器什么的?
解决方案
推荐阅读
- reactjs - 反应 pwa firebase 通知在 android 中不起作用
- python - 根据许多条件过滤数据框
- swift - 如何删除 tableView 单元格并从 firebase 中删除数据
- python - 如何对 Pandas 系列中的行求和?
- rust - 避免共享静态变量的“同步”
- java - 如何在 Junit 5 中使用 CsvFileSource 转义参数化测试中的双引号
- dataframe - 将 pyspark 数据帧值转换为可变字符串值
- java - 切换日/夜模式时如何为组件(工具栏、搜索栏、操作栏等)设置自定义颜色?
- nhibernate - 在字符串属性上搜索不等式
- reactjs - 如何使用 springboot 和 reactjs 正确配置 websocket?