DEV Community

Cover image for ANGULAR ERROR INTERCEPTORS
Angga Lesmana
Angga Lesmana

Posted on

ANGULAR ERROR INTERCEPTORS

What is interceptor in angular?
This is important for us as developer know about interceptor
so In Angular, an interceptor is a mechanism for handling or transforming HTTP requests and responses globally before they reach the components. It allows you to pre-process or post-process requests and responses. It is commonly used for tasks such as adding headers, handling errors, transforming data, etc.

why I say that an interceptor is important ? because they provide a way to handle HTTP requests and responses in a centralized and reusable manner, rather than having to write the same code in multiple places. This can improve the maintainability, readability, and testability of your code. Additionally, using interceptors can simplify common tasks such as adding headers or handling errors, reducing the amount of repetitive code and making it easier to make global changes.

Now Im gonna create the simple interceptor for handle error 401 response service

the first step we should create the interceptor, we can use commandline to generate interceptor

ng g interceptor error

Enter fullscreen mode Exit fullscreen mode

Angular will create the file error.interceptor.ts
like this

Image description

and will automaticly create the code interceptor like this

Image description

and we can add some code to detect error server

Image description

we will navigate the user is not login to login or to 401 page
but we already create the interceptor file we must import this to app.module.ts

Image description

And this will direct to 401 page

Image description

Top comments (0)