Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Defining error type to HttpClient.post()

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)
      );
like image 519
Patrick Avatar asked Jan 31 '26 10:01

Patrick


1 Answers

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)
);

Custom Error object

For more information on custom error handling, I would recommend you to go through this blog.

Hope this helps. Cheers and happy coding!!!

like image 72
Shravan Avatar answered Feb 02 '26 04:02

Shravan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!