-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror.js
40 lines (35 loc) · 965 Bytes
/
error.js
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
const {validationResult} = require('express-validator');
class AppError extends Error {
constructor(statusCode, errors) {
super();
this.statusCode = statusCode;
this.errors = errors;
}
}
class NotFoundError extends Error {
}
function errorHandler(err, req, res, next) {
if (err instanceof NotFoundError) {
res.sendStatus(404)
} else if (err instanceof AppError) { // validation failed
res.status(err.statusCode).json({errors: err.errors})
} else {
console.log(err);
res.status(500)
.json({error: err});
}
}
// custom middleware, checks if validation succeeded if not errorHandler will catch it
function validateRequest(req, resp, next) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
throw new AppError(400, errors.array())
}
next()
}
module.exports = {
NotFoundError,
AppError,
errorHandler,
validateRequest
};