1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | module.exports = function (config) {
|
15 | var renderer = require('./renderer')(config);
|
16 |
|
17 | var renderPageForContext = function (req, res, templateContext, fn) {
|
18 | renderer.render(req, res, templateContext, function (err, out) {
|
19 | if (err || !out) {
|
20 | config.log.warn('Rendering custom error page failed (misconfiguration?)');
|
21 | fn(null);
|
22 | } else {
|
23 | fn(out);
|
24 | }
|
25 | });
|
26 | };
|
27 |
|
28 | var getTemplateContext = function (err, req) {
|
29 | var key = typeof err.status === 'string' ? err.status : err.status.toString();
|
30 | var userData = config.errorPages;
|
31 | var layout = userData.errorLayouts.hasOwnProperty(key) ? userData.errorLayouts[key] : userData.errorLayouts.default;
|
32 |
|
33 | var templateContext = {
|
34 | layout: {
|
35 | template: layout,
|
36 | namespace: 'custom-errors'
|
37 | },
|
38 | errorContext: {
|
39 | error: err,
|
40 | hostname: config.env.host(),
|
41 | isDevelopment: config.env.isDevelopment(),
|
42 | isProduction: config.env.isProduction(),
|
43 | reqHost: req.headers.host,
|
44 | reqUrl: req.url
|
45 | }
|
46 | };
|
47 |
|
48 | if (userData.staticData) {
|
49 | for (var key in userData.staticData) {
|
50 |
|
51 | if (userData.staticData.hasOwnProperty(key) && !(key in templateContext)) {
|
52 | templateContext[key] = userData.staticData[key];
|
53 | }
|
54 | }
|
55 | }
|
56 |
|
57 | return templateContext;
|
58 | };
|
59 |
|
60 | return {
|
61 | getPage: function (err, req, res, fn) {
|
62 | if (!config.errorPages || !config.errorPages.errorLayouts || !config.errorPages.errorLayouts.default) {
|
63 | fn(null);
|
64 | } else {
|
65 | renderPageForContext(req, res, getTemplateContext(err, req), fn);
|
66 | }
|
67 | }
|
68 | };
|
69 | };
|