1 files changed, 39 insertions, 0 deletions
diff --git a/src/api/middlewares/errorMiddleware.js b/src/api/middlewares/errorMiddleware.js
new file mode 100644
index 0000000..b8de68e
--- /dev/null
+++ b/src/api/middlewares/errorMiddleware.js
@@ -0,0 +1,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
+ })
+ );
+ }
+}
|