Reputation: 2969
I have started to use the lastValueFrom() to handle my observable http requests. One of these http calls is returning an error from the server-side, and I am getting the name: 'EmptyError', message: 'no elements in sequence'
message
const response = await lastValueFrom(
this.service.doStuff()
).catch((e) => {
console.log('#1', e);
return {} as DoStuffResponse;
});
at #1 the error is EmptyError , not the error from the http call.
I understand why I am getting it (the http observable does not return a value)
However, what I'd like to know is what the actual error is (a 422 unprocessable entity in this case)
Is this possible ?
Upvotes: 4
Views: 8637
Reputation: 11077
I was having the same issue with NestJS. The solution was to wrap it in a try/catch clause:
async myFunctionOrMethod(
myPayload: any
): Promise<Result<Response, Err>> {
try {
const result = await lastValueFrom(
this.httpService.post('/api/endpoint', { myPayload})
);
return Ok(result.data as Response);
} catch (err) {
return Err(new InternalServerErrorException(err));
}
}
Upvotes: 1
Reputation: 1752
You do actually have the possibility to gracefully catch errors from lastValueFrom
like this:
firstValueFrom(this.http.post(url, body))
.catch((error: HttpErrorResponse) => {
console.log("error: ", error);
return "an error has occured"
}).then(response => {
// In case of an error this will receive "an error has occured" as a response
console.log("resp: ", response)
});
Upvotes: 3
Reputation: 193
I have not found a method to catch the Http errors from lastValueFrom and this does not appear to be documented in rxjs.
As a result I've decided to avoid lastValueFrom when doing Http requests. Instead I stick with Subscribe and always get the Http response codes in the error.
As an aside, many people noticed Subscribe as being deprecated in VSCode, but this is not true; just a certain overload. I know you didn't mention the deprecation as a motivator for using lastValueFrom, but I think most people, including myself, used the VSCode deprecation alert as a prompt to switch.
That said, this Subscribe syntax is still valid and should give you the Http error code:
this.someService.getResults.subscribe(
{
next: (results) => {
console.log('Here are the results...', results);
},
error: (err: any) => {
console.log('Here is the error...', err.status);
},
complete: () => { }
});
Upvotes: 2