'Nestjs control over errors
I'm processing a CSV file that's converted into JSON to make followup API calls. What is causing me a lot of pain is that I can't control the error returned, if it isn't 2xx then an error is thrown and stops the process. what I would like to do is something like this:
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)
}
Solution 1:[1]
This is actually an axios configuration. The validateStatus method of the request configuration can be used to customize what should happen on different error codes. In your case, it would look something like
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)
}
Do note that if you use the map operator as you currently are then res.status will not be data you can actually get to, because you assign res to the axios response's data property
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jay McDoniel |
