Reputation: 119
I want show the user a message if the HTTP request has an err_connection_refused
error. I am getting this error because the server is disconnected.
http.get().subscribe(
(response) => {
},
error => {
// some code to know error is err_connection_refused
}
);
Upvotes: 3
Views: 3733
Reputation: 13248
You can catch the error at the service level using the following RxJS 6 code:
http.get<YourType>().pipe(
map(result=>{
// do something here, such as accessing local storage, stopping a spinner...etc.
return result;
}),
catchError(err => {
return of (new YourType({}));
// or you can return throwError(err);
})
)
Upvotes: 1
Reputation: 56966
This is the approach you want. Just look at the err object in the console and see what the status is for connection refused:
http.get().pipe(
// here we can stop the error being thrown for certain error responses
catchError(err: HttpErrorResponse => {
console.log(err)
if (err.status == 404) return of(null)
else throwError(err)
})
).subscribe(
(response) => {
},
// if the error is thrown (or not caught if you do not use catchError) we hit this block
error => {
console.log(err.status)
// some code to know error is err_connection_refused
}
);
Upvotes: 0