-
Notifications
You must be signed in to change notification settings - Fork 194
/
status-handlers.js
111 lines (100 loc) · 2.32 KB
/
status-handlers.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
'use strict';
const he = require('he');
// not modified
exports['304'] = (res) => {
res.statusCode = 304;
res.end();
};
// access denied
exports['403'] = (res, next) => {
res.statusCode = 403;
if (typeof next === 'function') {
next();
} else if (res.writable) {
res.setHeader('content-type', 'text/plain');
res.end('ACCESS DENIED');
}
};
// disallowed method
exports['405'] = (res, next, opts) => {
res.statusCode = 405;
if (typeof next === 'function') {
next();
} else {
res.setHeader('allow', (opts && opts.allow) || 'GET, HEAD');
res.end();
}
};
// not found
exports['404'] = (res, next) => {
res.statusCode = 404;
if (typeof next === 'function') {
next();
} else if (res.writable) {
res.setHeader('content-type', 'text/plain');
res.end('File not found. :(');
}
};
exports['416'] = (res, next) => {
res.statusCode = 416;
if (typeof next === 'function') {
next();
} else if (res.writable) {
res.setHeader('content-type', 'text/plain');
res.end('Requested range not satisfiable');
}
};
// flagrant error
exports['500'] = (res, next, opts) => {
res.statusCode = 500;
if (!opts.handleError && next) {
next(opts.error);
return;
}
if (res.headersSent) {
res.destroy();
return;
}
res.setHeader('content-type', 'text/html');
const error = String(opts.error.stack || opts.error || 'No specified error');
const html = `${[
'<!doctype html>',
'<html>',
' <head>',
' <meta charset="utf-8">',
' <title>500 Internal Server Error</title>',
' </head>',
' <body>',
' <p>',
` ${he.encode(error)}`,
' </p>',
' </body>',
'</html>',
].join('\n')}\n`;
res.end(html);
};
// bad request
exports['400'] = (res, next, opts) => {
res.statusCode = 400;
if (typeof next === 'function') {
next();
} else {
res.setHeader('content-type', 'text/html');
const error = opts && opts.error ? String(opts.error) : 'Malformed request.';
const html = `${[
'<!doctype html>',
'<html>',
' <head>',
' <meta charset="utf-8">',
' <title>400 Bad Request</title>',
' </head>',
' <body>',
' <p>',
` ${he.encode(error)}`,
' </p>',
' </body>',
'</html>',
].join('\n')}\n`;
res.end(html);
}
};