-
Notifications
You must be signed in to change notification settings - Fork 0
/
error-handler.js
96 lines (86 loc) · 2.56 KB
/
error-handler.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { Merror } from 'express-merror';
import log from '../../utils/logger';
/**
* Extract an error stack or error message from an Error object.
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
*
* @param {Error} error
* @return {string} - String representation of the error object.
*/
export const getErrorMessage = (error) => {
/**
* If it exists, prefer the error stack as it usually
* contains the most detail about an error:
* an error message and a function call stack.
*/
const error_msg = { message: '', stack: '' };
if (error?.stack) {
console.log(error);
error_msg['stack'] = error.stack;
}
if (typeof error.toString === 'function') {
error_msg['message'] = error.toString();
}
return error_msg;
};
/**
* Log an error message to stderr.
*
* @see https://nodejs.org/dist/latest-v14.x/docs/api/console.html#console_console_error_data_args
*
* @param {string} error
*/
export const logErrorMessage = (error) => {
log('error', error);
};
/**
* Determines if an HTTP status code falls in the 4xx or 5xx error ranges.
*
* @param {number} statusCode - HTTP status code
* @return {boolean}
*/
export const isErrorStatusCode = (statusCode) => statusCode >= 400 && statusCode < 600;
/**
* Look for an error HTTP status code (in order of preference):
*
* - Error object (`status` or `statusCode`)
* - Express response object (`statusCode`)
*
* Falls back to a 500 (Internal Server Error) HTTP status code.
*
* @param {Object} options
* @param {Error} options.error
* @param {Object} options.response - Express response object
* @return {number} - HTTP status code
*/
export const getHttpStatusCode = ({ error, response }) => {
/**
* Check if the error object specifies an HTTP
* status code which we can use.
*/
const statusCodeFromError = error.status || error.statusCode;
if (isErrorStatusCode(statusCodeFromError)) {
return statusCodeFromError;
}
/**
* The existing response `statusCode`. This is 200 (OK)
* by default in Express, but a route handler or
* middleware might already have set an error HTTP
* status code (4xx or 5xx).
*/
const statusCodeFromResponse = response.statusCode;
if (isErrorStatusCode(statusCodeFromResponse)) {
return statusCodeFromResponse;
}
/**
* Fall back to a generic error HTTP status code.
* 500 (Internal Server Error).
*
* @see https://httpstatuses.com/500
*/
return 500;
};
export const reportMerror = (code, message, properties) => {
return new Merror(code, message, properties);
};