Is it possible to set the type of the return error to HttpClient.post()? I want to force anyone who is going to consume this service to use the properties that were defined in his error interface
Example:
// user.service.ts
sendData(data: User) {
return this.http
.post<User>(`${BASE_ENDPOINT}/user`, data, {
withCredentials: true
})
}
// user.component.ts
this.user.sendData(null)
.subscribe(
(success: User) => console.log(success),
(error: ResponseErrorUser) => console.log(error)
);
You can use Rxjs operators catchError and throwError to catch the error, map it into a custom object and throw this object.
import { catchError, throwError } from 'rxjs/operators';
...
...
// user.service.ts
sendData(data: User) {
return this.http
.post<User>(`/api/v1/not-available`, data, {
withCredentials: true
})
.pipe(
catchError(err => {
return throwError({
statusCode: err.status,
msg: err.message
});
})
);
}
// user.component.ts
this.sendData(null).subscribe(
(success: User) => console.log(success),
(error: { statusCode: number; msg: string }) => console.error(error)
);

For more information on custom error handling, I would recommend you to go through this blog.
Hope this helps. Cheers and happy coding!!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With