Nestjs 控制错误
Nestjs control over errors
我正在处理一个 CSV 文件,该文件已转换为 JSON 以进行后续 API 调用。让我很痛苦的是我无法控制返回的错误,如果它不是 2xx 则抛出错误并停止进程。
我想做的是这样的:
for await(const user of users) {
const res = await lastValueFrom(this.httpService.post<T>('example.com/create', body).pipe(map(res) => res.data))
if (res.status === 201 || res.status === 422) continue
else thrown new Error(res.data)
}
这实际上是一个axios配置。 request configuration 的 validateStatus
方法可用于自定义在不同的错误代码上应该发生什么。在你的情况下,它看起来像
for await(const user of users) {
const res = await lastValueFrom(
this.httpService.post<T>(
'example.com/create',
body,
{
// customize this as you want, or return true for always resolving the promise
validateStatus: (status) => true
}
).pipe(map(res) => res.data)
)
if (res.status === 201 || res.status === 422) continue
else thrown new Error(res.data)
}
请注意,如果您像现在一样使用 map
运算符,那么 res.status
将不是您实际可以获得的数据,因为您将 res
分配给了 axios 响应data
属性
我正在处理一个 CSV 文件,该文件已转换为 JSON 以进行后续 API 调用。让我很痛苦的是我无法控制返回的错误,如果它不是 2xx 则抛出错误并停止进程。 我想做的是这样的:
for await(const user of users) {
const res = await lastValueFrom(this.httpService.post<T>('example.com/create', body).pipe(map(res) => res.data))
if (res.status === 201 || res.status === 422) continue
else thrown new Error(res.data)
}
这实际上是一个axios配置。 request configuration 的 validateStatus
方法可用于自定义在不同的错误代码上应该发生什么。在你的情况下,它看起来像
for await(const user of users) {
const res = await lastValueFrom(
this.httpService.post<T>(
'example.com/create',
body,
{
// customize this as you want, or return true for always resolving the promise
validateStatus: (status) => true
}
).pipe(map(res) => res.data)
)
if (res.status === 201 || res.status === 422) continue
else thrown new Error(res.data)
}
请注意,如果您像现在一样使用 map
运算符,那么 res.status
将不是您实际可以获得的数据,因为您将 res
分配给了 axios 响应data
属性