forked from realdadfish/sparkleshare-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 3
/
error.js
57 lines (51 loc) · 1.45 KB
/
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
var util = require('util');
function NotFound(msg) {
this.name = 'Not Found';
this.message = msg ? msg : '';
Error.call(this, msg); // really do not know why this is not working! Fixed by setting message manually
Error.captureStackTrace(this, arguments.callee);
}
util.inherits(NotFound, Error);
function Permission(msg) {
this.name = 'Forbidden';
this.message = msg ? msg : '';
Error.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
}
util.inherits(Permission, Error);
function ISE(msg) {
this.name = 'Internal Server Error';
this.message = msg ? msg : '';
Error.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
}
util.inherits(ISE, Error);
function errorHandler(err, req, res, next) {
if (err instanceof NotFound) {
res.statusCode = 404;
} else if (err instanceof Permission) {
res.statusCode = 403;
} else {
res.statusCode = 500;
return next();
}
var accept = req.headers.accept || '';
if (~accept.indexOf('html')) {
// html
res.render('error', { e: err });
} else if (~accept.indexOf('json')) {
// json
var json = JSON.stringify({ error: err.name, msg: err.message });
res.setHeader('Content-Type', 'application/json');
res.end(json);
} else {
// plain text
res.setHeader('Content-Type', 'text/plain');
res.end(err.name + ": " + err.message);
}
}
module.exports = {
NotFound: NotFound,
Permission: Permission,
errorHandler: errorHandler
};