All files / bc-mongodb-implementation-demo/src/middleware error-handler.js

36.84% Statements 7/19
7.14% Branches 1/14
50% Functions 1/2
36.84% Lines 7/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 422x 2x   2x 4x   4x 4x                                                                 2x  
const { StatusCodes } = require('http-status-codes')
const { CustomAPIError } = require('../errors') // Import CustomAPIError
 
const errorHandler = (err, req, res, next) => {
  console.error(err) // Log the full error for debugging
 
  Eif (err instanceof CustomAPIError) {
    return res.status(err.statusCode).json({ msg: err.message })
  }
 
  let customError = {
    statusCode: err.statusCode || StatusCodes.INTERNAL_SERVER_ERROR,
    msg: err.message || 'Something went wrong, please try again later',
  }
 
  // Mongoose bad ObjectId
  if (err.name === 'CastError') {
    customError.msg = `No item found with id : ${err.value}`
    customError.statusCode = StatusCodes.NOT_FOUND
  }
 
  // Mongoose duplicate key
  if (err.code && err.code === 11000) {
    customError.msg = `Duplicate value entered for ${Object.keys(
      err.keyValue,
    )} field, please choose another value`
    customError.statusCode = StatusCodes.BAD_REQUEST
  }
 
  // Mongoose validation error
  if (err.name === 'ValidationError') {
    customError.msg = Object.values(err.errors)
      .map((item) => item.message)
      .join(',')
    customError.statusCode = StatusCodes.BAD_REQUEST
  }
 
  return res.status(customError.statusCode).json({ msg: customError.msg })
}
 
module.exports = errorHandler