Install Middleware – Step 4

Install Middleware – Step 4

Step 4: -Install Middleware

  1. Install middleware using command npm i morgan i.e. HTTP request logger middleware for node.js
  2. const morgan = require(‘morgan’);

if (process.env. NODE_ENV==”DEVELOPMENT”)

{          app.use(morgan(‘dev’))

}

Create 2 new folders with name middleware and util for Error Handling.

Middleware=>async.js

const asyncHandler = fn=>(req,res,next)=>
Promise.resolve(fn(req,res,next)).catch(next);
module.exports=asyncHandler

Middleware=>error.js

const ErrorResponse = require('../util/errorResponse')
const errorHandler = (err,req,res,next)=>
{
    let error = {...err};
    error.message=err.message;
    console.log(err);
    if(err.name==='CastError'){
        const message=`User not found with id of ${err.value}`;
        error= new ErrorResponse(message,404)
    }
    if(err.code===11000)
    {
        const message='duplicate field value';
        error= new ErrorResponse(message,400)
    }
    if(err.name==='ValidationError'){
         const message=Object.values(err.errors).map(val=>val.message);
        error= new ErrorResponse(message,400)
    }
    res.status(error.statusCode || 500).json({
        suceess:false,
        error:error.message || 'Server Error'
    });
};
module.exports = errorHandler;

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*