-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror-handler.ts
More file actions
56 lines (52 loc) · 1.58 KB
/
error-handler.ts
File metadata and controls
56 lines (52 loc) · 1.58 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
import { ErrorRequestHandler } from "express";
import { CustomError } from "../errors/custom-error";
export const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
// if the error is a CastError, send a 400 error and log the error
// CastError is a Mongoose error that occurs when a value is not of the correct type
// in this case, we are sending a 400 error and logging the error
if (err.name === "CastError") {
return res.status(400).send({
status: "error",
errors: [
{
field: err.path,
message: "شناسه کاربر معتبر نیست",
},
],
});
}
// if the error is a duplicate key error, send a 400 error and log the error
// duplicate key error is a Mongoose error that occurs when a value is not unique
// in this case, we are sending a 400 error and logging the error
if (err.code === 11000 && err.keyPattern?.email) {
return res.status(400).send({
status: "error",
errors: [
{
field: err.path,
message: "این ایمیل قبلا استفاده شده است",
},
],
});
}
// if the error is an instance of CustomError,
// then send the error with the status code and the serialized errors
if (err instanceof CustomError) {
return res.status(err.statusCode).send({
status: "error",
errors: err.serializeErrors(),
});
}
// if the error is not an instance of CustomError,
// send a 500 error and log the error
console.error(err);
return res.status(500).send({
status: "error",
errors: [
{
field: null,
message: "یک چیزی خیلی اشتباه پیش رفت",
},
],
});
};