errhandler-rca 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/errorHandler.js +38 -0
  2. package/package.json +11 -0
@@ -0,0 +1,38 @@
1
+ const { CommandSucceededEvent } = require("mongodb");
2
+
3
+ const errorHandler = (err, req, res, next) => {
4
+ console.error(err.stack);
5
+
6
+ //Mongoose Validational error
7
+ if (err.name === 'ValidationError') {
8
+ const message = Object.values(err.errors).map(e => e.message);
9
+ return res.status(400).json({
10
+ success: false,
11
+ error: message.join(', ')
12
+ })
13
+ }
14
+
15
+ //Mongoose Bad objectId
16
+ if (err.name === 'CastError') {
17
+ return res.status(404).json({
18
+ success: false,
19
+ error: 'Resource Not Found'
20
+ })
21
+ }
22
+
23
+ //Mongoose Duplicate key(Handling Duplicated Keys)
24
+ if (err.code === 11000) {
25
+ return res.status(400).json({
26
+ success: false,
27
+ error: 'Duplicated Field Value Entered'
28
+ })
29
+ }
30
+
31
+ //Handling a default erro
32
+ res.status(err.statusCode || 500).json({
33
+ success: false,
34
+ error: err.message || 'Server Error'
35
+ })
36
+ };
37
+
38
+ module.exports = errorHandler
package/package.json ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "errhandler-rca",
3
+ "version": "1.0.0",
4
+ "description": "this package will help people handle errors when using Nodejs to use in thier backend systems",
5
+ "main": "errorHandler.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "author": "Bruce-rca",
10
+ "license": "ISC"
11
+ }