This repository has been archived by the owner on Jun 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
77 lines (57 loc) · 1.64 KB
/
server.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
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const logger = require('morgan');
const stackTrace = require('stack-trace');
const errorhandler = require('errorhandler');
const config = require('./config');
const uptimeHelper = require('./helpers/uptime');
require('./models/db');
uptimeHelper.init();
const port = process.env.PORT || config.app.port;
const app = express();
app.use(bodyParser.json());
if (config.app.logger.enable) {
app.use(logger(config.app.logger.format));
}
app.use(errorhandler());
const routes = require('./routes');
app.use(routes);
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
/*** error handlers ***/
// Catch unauthorised errors
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
res.status(401);
res.json({ 'message': err.name + ': ' + err.message });
}
next(err);
});
// Error handler
app.use((err, req, res, next) => {
const trace = stackTrace.parse(err);
let errorResponse = {
message: err.message,
status: err.status,
stack: trace
};
var finalResponse = errorResponse;
// no stacktraces leaked to user in production only providing error in development
if (req.app.get('env') !== 'development') {
finalResponse = err.publicData ? err.publicData : {};
} else {
console.error(finalResponse); // eslint-disable-line no-console
}
res.status(err.status || 500)
.json(finalResponse);
next(err);
});
app.listen(port, () => {
console.log(`Express server listening on port ${port}`); // eslint-disable-line
});
module.exports = app;