How to send error notification instead of next notification in an observable stream?

Viewed 41

I have an API which responds an object like this:

{
       "statusCode": 200,
       "errors": [],
       "data": []
}

Sometimes it responds with data and sometimes responds with an array of errors. but the status code in headers always is 200 (OK). so the subscriber always gets next notification in observable stream even if the respond has some errors. the question is how can I transform the next notification to error notification in observable stream so the subscriber get error notification like when the request is not (OK). I can't use throw new Error() because it only can accept string while I want to give subscriber response object.

1 Answers

I suggest you to build an interceptor to do it. Something like this:

@Injectable()
export class ErrorResponseInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      map((response) => {
        if (!(response instanceof HttpResponse)) {
          return response;
        }
        if (
          !Object.keys(response.body).includes('errors') ||
          response.body.errors.length == 0
        ) {
          return response;
        }

        return new HttpResponse({
          body: response.body.errors,
          status: 500,
          statusText: 'Internal server error',
          url: response.url ?? undefined,
        });
      })
    );
  }
}

Then register this interceptor in your app.module:

providers: [
  {
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorResponseInterceptor,
    multi: true,
  },
],
Related