summary refs log tree commit diff
path: root/src/api/middlewares/errorMiddleware.js
blob: b8de68e8e428a5d7183bdfc202a5103fa50f0442 (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
import { SafeNSoundError } from '#util/error.js';
import { MongoServerError } from 'mongodb';

export function handleErrors(err, req, res, _next) {
    if (err instanceof MongoServerError) {
        if (err.code === 11000) {
            // Duplicate key error
            const newErr = 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]]
            });

            err = newErr;
        }
    }

    if (err instanceof SafeNSoundError) {
        console.log('meow');
        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
            })
        );
    }
}