Skip to content

Commit

Permalink
perf: front-load HTML template and stylesheet at middleware construction
Browse files Browse the repository at this point in the history
  • Loading branch information
dougwilson committed Apr 21, 2016
1 parent 6fbafc5 commit 7bbfeac
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 24 deletions.
1 change: 1 addition & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ unreleased
==========

* Pretty print JSON error response
* perf: front-load HTML template and stylesheet at middleware construction
* perf: resolve file paths at start up

1.4.3 / 2016-01-17
Expand Down
46 changes: 22 additions & 24 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ exports = module.exports = function errorHandler(options) {
log = logerror
}

// load html and style
var html = fs.readFileSync(TEMPLATE_PATH, 'utf8')
var style = fs.readFileSync(STYLESHEET_PATH, 'utf8')

return function errorHandler(err, req, res, next){
// respect err.statusCode
if (err.statusCode) {
Expand Down Expand Up @@ -119,30 +123,24 @@ exports = module.exports = function errorHandler(options) {

// html
if (type === 'html') {
fs.readFile(STYLESHEET_PATH, 'utf8', function (e, style) {
if (e) return next(e);
fs.readFile(TEMPLATE_PATH, 'utf8', function (e, html) {
if (e) return next(e);
var isInspect = !err.stack && String(err) === toString.call(err)
var errorHtml = !isInspect
? escapeHtmlBlock(str.split('\n', 1)[0] || 'Error')
: 'Error'
var stack = !isInspect
? String(str).split('\n').slice(1)
: [str]
var stackHtml = stack
.map(function (v) { return '<li>' + escapeHtmlBlock(v) + '</li>' })
.join('')
var body = html
.replace('{style}', style)
.replace('{stack}', stackHtml)
.replace('{title}', escapeHtml(exports.title))
.replace('{statusCode}', res.statusCode)
.replace(/\{error\}/g, errorHtml)
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end(body)
});
});
var isInspect = !err.stack && String(err) === toString.call(err)
var errorHtml = !isInspect
? escapeHtmlBlock(str.split('\n', 1)[0] || 'Error')
: 'Error'
var stack = !isInspect
? String(str).split('\n').slice(1)
: [str]
var stackHtml = stack
.map(function (v) { return '<li>' + escapeHtmlBlock(v) + '</li>' })
.join('')
var body = html
.replace('{style}', style)
.replace('{stack}', stackHtml)
.replace('{title}', escapeHtml(exports.title))
.replace('{statusCode}', res.statusCode)
.replace(/\{error\}/g, errorHtml)
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.end(body)
// json
} else if (type === 'json') {
var error = { message: err.message, stack: err.stack };
Expand Down

0 comments on commit 7bbfeac

Please sign in to comment.