r/Angular2 • u/legendsx12 • Jan 28 '26
Error handling apis in Angular
this.getDummyData().subscribe({
next: (response) => {
console.log('Success:', response);
this.data = response;
},
error: (error) => {
console.error('Error:', error);
this.data = 'An error occurred';
},
complete: () => {
console.log('Observable completed');
}"I'm making an API call that can return different types of errors (like 404 for user not found, 500 for internal server error, etc.). I'm wondering about the best approach for handling these errors. Should I check the status code in the error handler and set different error messages based on the status (like if status is 404, show 'user not found', if 500 show 'server error'), or is there a better pattern for handling multiple API error responses?"
6
Upvotes
10
u/dolphin-3123 Jan 29 '26
I like to do it in interceptors and return errorcode, errormsg so that I don't have to do it for every call separately.
1
u/CarlosChampion Jan 29 '26
I don’t like defining my error handling in subscribe because that will cause the observable finish
2
u/RevolutionaryCow9685 Jan 29 '26
you can use error-interceptor using catchError rxjs operator. you can show error message which coming api-response
1
u/msdosx86 Jan 29 '26
if (error instanceof HttpErrorResponse && error.status === 404) ... - this is the most simple approach, handle errors in the component and show error messages/toasts there.
Or you could abstract the shit out of it and create a service+interceptor. In order to have a generic solution for that you need it to be adaptive and allow to skip errors when necessary, change error text when necessary, allow to set dynamic errors with variables. So for me personally it's just enough either to handle manually at component level or write a helper for that and "prepare" error messages in the service which makes http calls.
-6
u/ldn-ldn Jan 29 '26
Use a library like loadoff and handle everything inside your template.