Error Handling
Error Handling Interview with follow-up questions
1. What is error handling in Angular and why is it important?
Error handling is how an app anticipates, catches, and responds to failures — failed HTTP calls, runtime exceptions, validation problems — so it degrades gracefully instead of crashing or leaving the user stuck. It matters because it directly shapes UX (clear messages, retry options), reliability (the app keeps running), security (don't leak internals), and observability (errors get logged for diagnosis).
Angular gives you layered tools, and a strong answer names where each applies:
- RxJS
catchError— handle failures in observable streams (HTTP, etc.). - Functional HTTP interceptors — centralize cross-cutting handling (auth refresh, 5xx, toast notifications) for all requests.
- Global
ErrorHandler— a single hook for otherwise-uncaught client errors, ideal for logging to a service like Sentry.
The principle interviewers want: handle errors at the right layer, show the user something useful, and report the rest — never swallow errors silently.
Follow-up 1
Can you explain how to handle errors in Angular?
In Angular, errors can be handled using various techniques. Some common approaches include:
Using try-catch blocks: Wrap the code that might throw an error in a try block and catch the error in a catch block. This allows you to handle the error and take appropriate actions.
Using error handlers: Angular provides error handling mechanisms such as the ErrorHandler class and the global error handler. These can be used to catch and handle errors at a global level.
Using observables: Angular leverages the RxJS library, which provides operators like catchError that can be used to handle errors emitted by observables.
Logging errors: Logging errors can help in debugging and identifying the root cause of the error. Angular provides logging mechanisms like the console.error() function or third-party logging libraries.
The approach to error handling depends on the specific requirements of the application and the nature of the errors.
Follow-up 2
What are some common errors you might encounter in Angular?
Some common errors that you might encounter in Angular include:
Null or undefined values: These errors occur when you try to access properties or methods on null or undefined values.
Type errors: Type errors occur when you try to perform operations on incompatible types or when the expected type does not match the actual type.
HTTP errors: When making HTTP requests in Angular, you might encounter errors such as 404 (Not Found), 500 (Internal Server Error), or network-related errors.
Template errors: Template errors occur when there are issues with the HTML templates, such as syntax errors or missing template variables.
Dependency injection errors: These errors occur when there are issues with dependency injection, such as missing or circular dependencies.
These are just a few examples, and the specific errors you encounter will depend on the complexity and nature of your Angular application.
Follow-up 3
How can you prevent these errors?
To prevent errors in Angular, you can follow these best practices:
Use strict type checking: Enable strict mode and TypeScript's type checking to catch type errors at compile-time.
Perform null and undefined checks: Always check for null or undefined values before accessing properties or calling methods.
Use defensive programming techniques: Validate inputs, handle edge cases, and use defensive coding practices to prevent unexpected errors.
Handle HTTP errors: Implement error handling mechanisms for HTTP requests, such as using the catchError operator to handle errors emitted by observables.
Validate templates: Use Angular's template validation tools to catch template errors during development.
Use dependency injection correctly: Ensure that dependencies are properly injected and avoid circular dependencies.
By following these practices, you can reduce the likelihood of encountering errors and improve the stability and reliability of your Angular application.
2. What is HTTP error handling in Angular?
HTTP error handling deals with failed requests from HttpClient — network errors and non-2xx responses, which arrive as an HttpErrorResponse. You distinguish client/network errors (error.error instanceof ProgressEvent, status === 0) from server errors (4xx/5xx with a status and body).
The idiomatic approach is catchError in the pipeline plus retry for transient failures, and a functional interceptor to centralize handling:
export const errorInterceptor: HttpInterceptorFn = (req, next) =>
next(req).pipe(
catchError((err: HttpErrorResponse) => {
if (err.status === 401) inject(Auth).logout();
inject(Toast).show(err.error?.message ?? 'Request failed');
return throwError(() => err);
})
);
// provideHttpClient(withInterceptors([errorInterceptor]))
Points worth making: register interceptors with withInterceptors([...]) (functional, the modern way — class-based HTTP_INTERCEPTORS is legacy); inspect status/HttpStatusCode to branch; and if you use the newer httpResource, it exposes an error signal you can render directly.
Follow-up 1
Can you explain how HTTP error handling works in Angular?
In Angular, HTTP error handling can be achieved using the HttpClient module and its HttpErrorResponse class. When an HTTP request fails, the HttpClient module emits an error event that can be subscribed to. The HttpErrorResponse object contains information about the error, such as the status code and error message. Angular provides various ways to handle these errors, such as using the catchError operator to handle errors in an observable chain, or using interceptors to globally handle errors.
Follow-up 2
What are some common HTTP errors and how would you handle them in Angular?
Some common HTTP errors include 404 (Not Found), 500 (Internal Server Error), and 401 (Unauthorized). In Angular, these errors can be handled in different ways depending on the specific use case. Here are some examples:
Handling 404 errors: If a resource is not found, you can handle the error by displaying a user-friendly message or redirecting the user to a different page.
Handling 500 errors: If an internal server error occurs, you can log the error for debugging purposes and display a generic error message to the user.
Handling 401 errors: If a user is not authorized to access a resource, you can redirect them to a login page or display an access denied message.
These are just a few examples, and the actual handling of HTTP errors in Angular will depend on the specific requirements of your application.
3. How can you create a custom error handler in Angular?
Implement Angular's ErrorHandler interface and override its single method, handleError(error), then register your class to replace the built-in handler:
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
private logger = inject(LoggingService);
handleError(error: unknown): void {
this.logger.report(error); // send to Sentry/Datadog, etc.
// optionally show a user-facing notification
}
}
// app.config.ts
providers: [{ provide: ErrorHandler, useClass: GlobalErrorHandler }]
This catches otherwise-unhandled errors app-wide — perfect for centralized logging. Things to note: in modern standalone apps you register it in the providers of bootstrapApplication/ApplicationConfig (not an NgModule); use inject() carefully since the handler is created early in bootstrap; and remember the global handler is a safety net, not a substitute for handling expected failures (like HTTP errors) closer to where they occur with catchError/interceptors.
Follow-up 1
Can you give an example of a custom error handler?
Sure! Here's an example of a custom error handler in Angular:
import { ErrorHandler } from '@angular/core';
export class CustomErrorHandler implements ErrorHandler {
handleError(error: any): void {
// Custom error handling logic goes here
console.error('An error occurred:', error);
}
}
In this example, the CustomErrorHandler class implements the ErrorHandler interface and defines the handleError method to log the error to the console. You can replace the console logging with your own error handling logic, such as displaying an error message to the user or sending the error to a logging service.
Follow-up 2
What are the benefits of creating a custom error handler?
Creating a custom error handler in Angular provides several benefits:
Centralized error handling: By creating a custom error handler, you can centralize the handling of errors in your application. This allows you to define a consistent error handling strategy and avoid duplicating error handling code in multiple places.
Custom error logging: With a custom error handler, you have full control over how errors are logged. You can log errors to the console, send them to a logging service, or perform any other custom logging logic.
Graceful error handling: A custom error handler allows you to handle errors in a more graceful manner. Instead of letting unhandled errors crash the application, you can catch and handle them in a way that provides a better user experience.
Error recovery: In some cases, you may want to recover from certain types of errors and continue the execution of your application. With a custom error handler, you can implement error recovery logic and prevent the application from completely breaking when an error occurs.
4. What is the role of the ErrorHandler class in Angular?
ErrorHandler is Angular's global, centralized hook for uncaught errors. Angular provides a default implementation that logs errors to the console; you can replace it with your own by providing a class that implements ErrorHandler and overrides handleError(error).
Its role is to be the last line of defense: any exception not caught elsewhere — in a lifecycle hook, an event handler, or a synchronous part of the app — flows to handleError, giving you one place to log/report and optionally notify the user.
The boundaries interviewers like you to know:
- It catches errors in Angular's execution context, but you still handle expected async/HTTP failures locally with
catchError/interceptors — those don't reachErrorHandlerunless rethrown. - Provide your custom handler in the app's root
providers(standaloneApplicationConfig) via{ provide: ErrorHandler, useClass: ... }. - It's the natural integration point for error-monitoring tools (Sentry, etc.).
Follow-up 1
How can you use the ErrorHandler class to handle errors in Angular?
To use the ErrorHandler class to handle errors in Angular, you need to create a custom error handler that extends the ErrorHandler class. This custom error handler can then be registered in the application's providers to replace the default ErrorHandler. Within the custom error handler, you can implement the handleError() method to define how errors should be handled. For example, you can log the error, display a user-friendly error message, or perform any other necessary actions.
Follow-up 2
Can you override the ErrorHandler class? If so, how?
Yes, you can override the ErrorHandler class in Angular by creating a custom error handler that extends the ErrorHandler class. To override the ErrorHandler class, you need to create a new class that extends ErrorHandler and implement the handleError() method to define the custom error handling logic. Once the custom error handler is created, you can register it in the application's providers to replace the default ErrorHandler. This allows you to customize how errors are handled in your Angular application.
5. How can you handle errors in Observables in Angular?
Handle observable errors with the RxJS catchError operator inside pipe(). In the handler you recover (return a fallback stream with of(...)), or rethrow with throwError(() => ...) so callers can react:
this.api.getUser(id).pipe(
retry({ count: 2, delay: 1000 }), // retry transient failures
catchError((err: HttpErrorResponse) => {
this.logger.error(err);
return of(EMPTY_USER); // graceful fallback
// or: return throwError(() => new Error('Could not load user'));
})
).subscribe();
Points worth adding: an observable's error notification terminates the stream, so for long-lived streams put catchError where it won't kill the outer subscription, or use retry/retryWhen to resubscribe. Related operators include retry, finalize (cleanup regardless of outcome), and EMPTY/of for recovery values. Note the older throwError('msg') signature is deprecated — use the factory form throwError(() => new Error('msg')). And the .subscribe(next, error, complete) form is deprecated in favor of an observer object { next, error }.
Follow-up 1
Can you explain the catchError operator in Angular?
The catchError operator in Angular is used to catch and handle errors emitted by an Observable. It takes a callback function as an argument, which is called whenever an error is emitted. Inside the callback function, you can handle the error as needed, and optionally return a new Observable or throw an error to propagate the error further. Here is an example of how to use catchError:
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
myObservable.pipe(
catchError(error => {
// Handle the error here
return throwError('An error occurred');
})
).subscribe();
In the above example, the catchError operator is used to catch any errors emitted by the myObservable. Inside the catchError callback, you can handle the error as needed. You can also choose to re-throw the error using the throwError function if you want to propagate the error further.
Follow-up 2
How can you retry a failed HTTP request in Angular?
In Angular, you can retry a failed HTTP request using the retry operator. This operator allows you to automatically re-attempt the request a specified number of times in case of failure. Here is an example of how to use the retry operator:
import { retry } from 'rxjs/operators';
httpClient.get('https://api.example.com/data').pipe(
retry(3) // Retry the request 3 times
).subscribe();
In the above example, the retry operator is used to retry the HTTP request 3 times in case of failure. You can specify the number of retries as an argument to the retry operator. If the request still fails after the specified number of retries, the error will be propagated to the error handling logic.
Live mock interview
Mock interview: Error Handling
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.