DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Custom Error Class in Angular 12+
Enes Karataş
Enes Karataş

Posted on

Custom Error Class in Angular 12+

How to create custom error class in Angular ?

Sometimes you don't want to use the default error class already exists so, in these times you need to write your own error class. To do that you should follow several steps and we are going to investigate all step by step.

In this essay I have just built my own custom error class so that you don't have to use the same logic. You can modify your class using your OOP knowledges and logic. Anyways let's code it !

Angular will be used in this case so that If you don't have yet you should have it before. To get this please visit this site angular.io.


Creating new angular project

First create a new angular project on the terminal/powershell then open the project folder on the editor. My current editor is Visual Studio Code.

Note that you should allow routing while creating the application.

ng new 'project name'

cd 'project folder'

ng serve

If you use vscode you can run the project using new terminal on the navbar.

Alright now it is time to implement on the project. I am not going to implement the changes on the app component directly, instead I will create another component to do that.

cd src/app
mkdir pages
cd pages
ng g c customError

To see the page of component you should add the route path to app-routing.module.ts.

   const routes: Routes = [
     { path: 'customError', component: CustomErrorComponent }
   ];
Enter fullscreen mode Exit fullscreen mode

Once the application is run you are going to see that the page works! So far so good!

To create a custom class and use in error component I am going to use angular model type. Under the app folder create a new folder named as models. Open new terminal in the models and look at the followings.

cd models
ng g class CustomError --type=model

CustomError class has been created in the models folder. We will implement the all changes on this class.

Now you have an empty file named like custom-error.model.ts so, it is time to define a class like following code.

custom-error.model.ts

export class CustomError extends Error {
    constructor(
        msg: string,
        private statusCode?: number, // optional variable
    ) {
        super(msg);
        Object.setPrototypeOf(this, CustomError.prototype);
    }
    alertError(): string{
        return this.statusCode ? `Custom Error: Status => ${this.statusCode}, Message => ${this.message}` : `Custom Error: Message => ${this.message}`;
    }
}
Enter fullscreen mode Exit fullscreen mode

In the code above we have just defined the class we want and this class extends to Error class defined by default in typescript. As you could see there is an another optional variable named like statusCode under the msg. To give an error code to the class it will be used.

Let's go to the component ! Model is called on the top of the custom-error.component.ts like the following and I've just written a function callCustomErrorModel to call our class that I have created.

import { CustomError } from 'src/app/models/custom-error.model';
Enter fullscreen mode Exit fullscreen mode
  errorMessage: any;
  constructor() { 
    this.callCustomErrorModel();
  }

  callCustomErrorModel(){
    let newError = new CustomError('this is new error instance', 101);
    if(newError instanceof CustomError) {
      this.errorMessage = newError.alertError();
    }
  }
Enter fullscreen mode Exit fullscreen mode

You are going to see the message on the page while you go to the url localhost:4200/customError.

Definitely you can get the all codes and improve them so access the codes here.

Top comments (0)

What image format should you use in your next project? πŸ€”