How to add a Middleware and a Function to Handle Errors?

How to add a Middleware and a Function to Handle Errors

Write a function in index.js:-

app.use((err, req, res, next)=>{
    const statusCode=err.statusCode || 500;
    const message=err.message || “Internal Server Error”;
    res.status(statusCode).json({
        success:false,
        statusCode,
        message
    })
})
 
 

Add “next” parameter in signup function in “auth.controller.js” –

next

Add next in catch –

 

next error

Create a folder “utils” inside API folder

Create a file “error.js” inside utils folder

error.js:

export const errorHandler=(statusCode, message)=>{
    const error=new Error();
    error.statusCode=statusCode;
    error.message=message;
    return error;
}
 

Use this errorhandler in “auth.controller.js” –

 
errorhandler
 
 test this in postman –
 
 
 

Video Tutorial: –