-
Notifications
You must be signed in to change notification settings - Fork 0
/
example-express-app.js
64 lines (54 loc) · 1.29 KB
/
example-express-app.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
// Imports
const Logger = require('@simplybusiness/twiglet')
const express = require('express')
// Constants
const PORT = 8080
// Define a logger
const log = Logger('petshop')
// Define some express middleware
const loggingMiddleware = (req, res, next) => {
log.info({
event: { action: 'http request' },
message: 'request received',
http: {
url: {
path: req.path,
query: req.query,
original: req.originalUrl
},
request: { method: req.method.toLowerCase() },
response: { status_code: 200 }
}
})
next()
}
const errorHandler = (err, req, res, next) => {
if (res.headersSent) {
return next(err)
}
// Probably no need for URL/request info here as request
// already logged by previous middleware
log.error({
message: 'Error',
response: { status_code: 500 }}, err)
res.status(500)
res.render('An error has occurred')
}
// Our server
var app = express()
app.use(loggingMiddleware)
app.get('/', (req, res) => {
res.send('This is the home Page')
})
app.get('/broken', (req, res) => {
throw(new Error('Emergency!'))
})
app.use(errorHandler)
// Start our petshop
app.listen(PORT, () => {
log.info({
event: { action: 'startup' },
message: `Ready to go, listening on port ${PORT}`,
server: { port: PORT }
})
})