What is error handling in Angular?

An error arises when a program’s execution has unexpected results. There are 3 usual errors in Angular:

  1. External
  2. Internal
  3. Application

Error handling in Angular is done with the help of the handleError function. This function allows centralized exception handling and is provided to the application when the application is initialized.

Class

The handleError function is a part of the errorHandler class.

Parameter

The handleError function takes the exception raised as a parameter.

Output

The handleError function, by default, only prints error messages to the console. However, a customized exception handler can be added to intercept and modify the default behavior.

Code

The following code explains the syntax for errorHandler class. This is the default implementation that can be changed.

class MyErrorHandler implements ErrorHandler {
//this function is called when the application throws an error
handleError(error: Error) {
// handle the exception here
}
}
@NgModule({
providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
})
class MyModule {}
Copyright ©2024 Educative, Inc. All rights reserved