-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
executable file
·62 lines (52 loc) · 1.81 KB
/
index.ts
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
57
58
59
60
61
62
import type { Response } from 'express';
interface StatusError extends Error {
status?: number;
statusCode?: number
safe?: string;
}
/**
* @class
*/
export default class PublicError extends Error {
status: number;
safe: string;
constructor(status: number, err?: Error | null, safe?: string, print = true) {
// Wrap postgres errors to ensure stack trace (line nums) are returned
if (err && Object.hasOwn(err, 'severity')) err = new Error(err.message);
super(err ? err.message : safe);
if (print && ![400, 401, 402, 403, 404].includes(status)) console.error(err ? err : 'Error: ' + safe);
this.status = status;
this.safe = safe || 'Generic Error';
this.name = 'PublicError';
Error.captureStackTrace(this, this.constructor);
}
static respond(err: unknown, res: Response, messages: object[] = []) {
if (typeof err === 'object') {
const serr = err as StatusError;
const status = Object.hasOwn(serr, 'status') ? (!isNaN(Number(serr.status)) ? Number(serr.status) : 500 ) : 500;
if (status === 500) {
console.error(err);
}
if (!res.headersSent) {
res.status(status).send({
status: status,
message: Object.hasOwn(serr, 'safe') ? serr.safe : 'Internal Server Error',
messages
});
} else {
res.end();
}
} else {
console.error(err);
if (!res.headersSent) {
res.status(500).send({
status: 500,
message: 'Internal Server Error',
messages
});
} else {
res.end();
}
}
}
}