rxjs

handle http errors in rxjs lastValueFrom


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 ?


Solution

  • 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: () => { }
    
    });