import { SafeNSoundError } from '#util/error.js'; import { MongoServerError } from 'mongodb'; import joi from 'joi'; export function handleErrors(err, req, res, _next) { if (err instanceof MongoServerError) { if (err.code === 11000) { // Duplicate key error err = new SafeNSoundError({ errCode: 'DUPLICATE_KEY_ERROR', message: 'A duplicate key error occurred.', key: Object.keys(err.keyPattern)[0], value: err.keyValue[Object.keys(err.keyValue)[0]] }); } } else if (err instanceof joi.ValidationError) { err = new SafeNSoundError({ errCode: 'JOI_VALIDATION_ERROR', message: err.message, validation_details: err.details }); } if (err instanceof SafeNSoundError) { console.error(err.stack); res.status(500).json(err); } else { // log and handle uncaught exceptions console.error( 'Unhandled error:', Object.getPrototypeOf(err), JSON.stringify(err, null, 2) ); console.error(err.stack); res.status(500).json( new SafeNSoundError({ errCode: 'INTERNAL_SERVER_ERROR', message: null, err }) ); } }