forked from vefforritun/vef2-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
07.error-handling.js
57 lines (41 loc) · 1.19 KB
/
07.error-handling.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
/* eslint-disable no-unused-vars */
/*
Keyrt með:
node 07.error-handling.js
Keyrum nokkur middleware á mismunandi máta.
*/
import express from 'express';
const app = express();
app.get('/', (req, res) => {
res.send('Hello world');
});
app.get('/hello/:name', (req, res, next) => {
const { name = '' } = req.params;
// Þekkjum ekki "óli"
if (name.toLocaleLowerCase() === 'óli') {
// sendum áfram í næsta middleware, mun enda í 404
return next();
}
// Ef við köstum villu hér mun hún verða gripin af errorHandler
// throw new Error('villa úr middleware');
return res.send(`Hello ${name}`);
});
app.get('/error', (req, res) => {
throw new Error('Villa!');
});
function notFoundHandler(req, res, next) {
res.status(404).send('404 Not Found');
}
function errorHandler(err, req, res, next) {
console.error(err);
res.status(500).send('Villa!');
}
app.use(notFoundHandler);
// Ef við skilgreinum ekki error handling middleware fáum við sjálfgefin
// skilaboð frá express um villu
app.use(errorHandler);
const hostname = '127.0.0.1';
const port = 3000;
app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});