summary refs log tree commit diff
path: root/src/api/middlewares/errorMiddleware.js
blob: 2ca31db3044fef43826f4ec91ee7274430796f76 (plain) (blame)
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
42
43
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
            })
        );
    }
}