In this video.
Let's go ahead and then improve this function a little bit by extracting the function to it on file.
And then we're going to require it inside the server file.
And that way we're going to have less code on the server JS file.
And for this one tool, we can improve this one a little bit.
So let's start with the how we can refactor this one and going to be pretty simple.
Remember, this one is a middleware, so we are going to create a folder for that.
So here we go in middle.
Where and for me where we can have different types.
For example, middleware for handling authentication or authorization, a middleware for handling errors.
So I'm going to create one folder for arrows, and here we go.
And I'll call this one as global error handler.
Dart JS and inside is a fire.
We are waiting to catch the call back here.
So inside the to use, we are going to cut everything inside that.
So when I cut it, you can see that everything has been removed.
And now back to this file.
I'm going to paste that one and I'm going to name it as const.
Global.
Error handler.
The name is apt you when I save it.
The next step is I need to export from this file module.
Dot exports is equal to global error handler.
Middle world.
So that is it.
So inside the server file I will go ahead and then require that.
So here we go to next step is our pass as a callback function to this.
As that.
So save it.
And now let's try again to initiate some error if we're going to happen.
So for this one, let's send some wrong ID and let's send and indeed everything is working fine.
The next step is about the photo for error handler.
So back to the server file for this one to we can reduce the number of code here because we have the
function called the app error, where we can create instance of error with a customized message.
We can do the same thing inside the photo for error handler here.
So this how are we going to do?
We are going to create a variable and assign the entire message into that.
So let's comment this one and let's begin with the implementation.
So here we go.
Cast error is equal to then I'll bring in the app error class.
And then for this one, I'm going to pass in the message, which is this.
So our policy as first agreement to this and lastly, I'll pass in the status code for oh four.
So now I can remove this one and last that is, I need to pass this message to the next.
So here we go.
You're going to be us next.
Now pass in the arrow and that is it.
So let's go ahead and make a request to Iraq, which has been defined.
So, for example, for a slash log E or for a slash account, if I hit send, you can see that I got
this message for a slight account not found.
Now everything is working fine.