I am communicating with an API that returns an http error when it can't find results.
For example when sending a get request to /api/fruits/xxxx the API responds with:
ERROR HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: 'Not Found', url: 'https://limitless-wave-57443.herokuapp.com/https://fruityvice.com/api/fruit/aaa', ok: false, …}
I need a way to instead return an empty array which I can use in my front-end to display a "No results found" caption. I tried using httpError interceptors but I can't figure out how to actually return this array
my interceptor:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
retry(0),
catchError((error: HttpErrorResponse) => {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// client-side error
errorMessage = `Error: ${error.error.message}`;
} else {
// server-side error
errorMessage = `Error Status: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(errorMessage);
})
)
}
CodePudding user response:
You can just use return of([]);
instead of rethrowing the error to just return an empty array instead of an error.