Angular Error Handling
Things go wrong in every application. A server goes offline, a visitor types a strange value, or a network connection drops on a train. Good error handling keeps the application calm during these moments. Visitors see a clear message, and developers receive the details they need to fix the cause.
The Smoke Alarm Idea
A smoke alarm does not prevent fires. It warns people early and gives them time to act. Error handling plays the same role in your code. It detects trouble, informs the visitor, and records the problem for you. A silent failure is worse than a loud one because nobody knows what broke.
Something fails
|
v
+------------------+
| Catch the error |
+------------------+
| |
v v
Tell the Record the
visitor details
(friendly) (for developers)
Types of Errors
- Network errors happen when the connection fails before the server answers.
- Server errors arrive with status codes such as 500 when the server has a problem.
- Client errors arrive with codes such as 404 when the requested item does not exist.
- Code errors happen inside your own logic, such as reading a property of an empty value.
Catch Errors in an HTTP Call
The catchError operator from RxJS handles a failed request. It lets you return a safe replacement value or pass the error forward.
import { catchError, of } from 'rxjs';
this.http.get<Book[]>('/api/books').pipe(
catchError(error => {
console.error('Load failed', error);
return of([]); // an empty list keeps the page working
})
).subscribe(books => this.books.set(books));The of([]) call supplies an empty list, so the page still renders.
Read the Status Code
The error object carries a status number. Match each number to a clear message.
function messageFor(status: number): string {
switch (status) {
case 0: return 'Check your internet connection.';
case 401: return 'Please log in again.';
case 404: return 'We could not find that item.';
case 500: return 'The server had a problem. Try again later.';
default: return 'Something went wrong.';
}
}Retry a Failed Request
Short network problems often disappear within seconds. The retry operator repeats the request automatically.
import { retry } from 'rxjs';
this.http.get('/api/books').pipe(retry(2));The number tells RxJS how many extra attempts to make. Use retries only for safe requests such as reading data. Repeating a payment request could charge a customer twice.
Handle Errors in One Place
An HTTP interceptor can catch every failed request in the application. It saves you from writing the same code in each service. Pair it with a small notification service that displays a message at the top of the screen.
The Global Error Handler
Angular lets you replace its default error handler. The new handler receives every uncaught error in the application. Use it to send reports to a logging service.
import { ErrorHandler, Injectable } from '@angular/core';
@Injectable()
export class AppErrorHandler implements ErrorHandler {
handleError(error: unknown) {
console.error('Unexpected error', error);
// send the details to your logging tool here
}
}
// registration
providers: [{ provide: ErrorHandler, useClass: AppErrorHandler }]Show Friendly Messages
Visitors do not need technical details. Write short messages that explain what happened and what to do next. "We could not save your changes. Please try again." works better than "Error 500: Internal exception". Keep the technical text in the console and the log.
Errors in Forms
Validation errors differ from server errors. They show visitors how to correct a value before submitting. Place each message directly under its field, and word it as a helpful instruction.
Choose the Right Tool
| Problem | Tool |
|---|---|
| One request fails | catchError in that call |
| Temporary network trouble | retry |
| Same handling for all requests | HTTP interceptor |
| Unexpected code error | Global ErrorHandler |
| Invalid user input | Form validators |
Key Points
- Catch errors early, and tell visitors what to do next.
- Use
catchErrorfor a single call andretryfor short network trouble. - Use an interceptor and a global handler for shared handling.
- Keep technical details in logs, not on the screen.
