(Comprehensive Step-by-Step Guideline)
Last night I was working on a large-scale project for one of my clients. Following the defined task, I was creating a couple of API calls to my server. When the project scales, the size of the code gets bigger, the new problems start taking place. The backend was throwing various errors based on API responses, and in the frontend, for handling this error, I had to wrap this function inside try and catch. To know more about this, go through this link.
So by the end of this blog, you will learn;
- We will learn what decorators are?
- Why do we use decorators?
- What are targets, names, and descriptors in decorators?
- We will write our own custom @TryCatch decorator
What are Decorators?
In a layman’s term, decorators are a piece of code that wraps with another functional composition or higher-order functions — literally ‘decorating’ it. This is a very basic higher-order function. CustomHigherOrderFunction takes a function as an argument and returns a wrapper of that function, which will append a decorator string in front of the passed string (hello world). So the output of the following function will be “Decorator hello world.”
Why do we use decorators?
Decorating a Class Method
So before creating a decorator, we have three main concepts of decorators that are;
- Target: The Object in which you’re doing some decorating. Here it is your Class
- Name: The name string you’re decorating.
- Descriptor: An object to the decorated method through the value property.
Here I have made a class to fetch some data from the backend, and for error handling, I have wrapped inside try-catch. But the problem here is I have to wrap this function inside try-catch every time we add new API endpoints. So let’s change it to decorators
As we can see here, we have made APIService class, which contains fetchTodos method and fetchTodos function to fetch todos from the server. Still, the significant thing to note down here is before method we have one decorator that is @TryCatch(), and here actual magic happens. So let’s see what actually contains inside TryCatch.
In this function, as we can see, the first argument is a target, which is here ApiService class; the second argument is the name that is here fetchTodos string, and the third argument is the descriptor. Most of the time, we will deal with the descriptor. So first, we will take descriptor.value and store it in a variable here as fn. Then we will override descriptor.value with async function, and which takes args as parameters and wrap inside try to catch inside try block we will call fn.apply(this, args) and return the response. If any error occurred, then it is advisable to go inside the catch block. So this is it for making a TryCatch decorator. Below you can find the complete code for this tutorial.