0

I am wondering how to properly handle and control errors in Angular & Web api, on some tutorial I saw that errors are handled in a component and not in a service which is fetching data.. and basically both backend and angular/clients erros are handled in a component like this:

enter image description here

I'm wondering how is possible that he handles both backend and frontend errors in a component? So does that mean I DON'T NEED TRY/CATCH IN A WEB API ? this should handle it also ?

I'm confused here, please explain me this example...

And I thought error handler should be added in a service.ts - in this example PeopleService, while PeopleService looks like this:

enter image description here

So I'm confused about this:

Shouldn't there be logic in a service.ts which would handle errors?

Shouldn't I wrote try/catch in a WebApi, how come backend errors are handled here?

Thanks for help guys Cheers!

billy_56
  • 649
  • 3
  • 11
  • 27

1 Answers1

0

In your example a backend error is something like the server responded with 404 (not found). For example you requested a specific person by id and the server did not find any person related to that id so it returns a response with 404. This way the client will know that the person the user is trying to find does not exist.

Shouldn't there be logic in a service.ts which would handle errors?

From Angular guide:

Error inspection, interpretation, and resolution is something you want to do in the service, not in the component.

Errors are encapsulated in an ErrorObservable in the service not the component.

then in your component you would do something like:

service.subscribe(
   result => this.result = result,
   error => console.log(error)
);

Shouldn't I wrote try/catch in a WebApi, how come backend errors are handled here?

You are not handling errors that occur in the backend. You are handling errors returned from the server response. For example: if there is an null reference error in your backend handling the error like your example will not save your server from crashing.

The backend is a process of its own. It has its own error handlers. The client code (angular) runs in the user's browser.

You could see the guide on angular site for more on this.

Omar
  • 343
  • 1
  • 11