comunicationLeap/node_modules/connect/lib/middleware/errorHandler.js
node_modules/connect/lib/middleware/errorHandler.jsRaw
1/*!
2 * Connect - errorHandler
3 * Copyright(c) 2010 Sencha Inc.
4 * Copyright(c) 2011 TJ Holowaychuk
5 * MIT Licensed
6 */
7
8/**
9 * Module dependencies.
10 */
11
12var utils = require('../utils')
13 , fs = require('fs');
14
15// environment
16
17var env = process.env.NODE_ENV || 'development';
18
19/**
20 * Error handler:
21 *
22 * Development error handler, providing stack traces
23 * and error message responses for requests accepting text, html,
24 * or json.
25 *
26 * Text:
27 *
28 * By default, and when _text/plain_ is accepted a simple stack trace
29 * or error message will be returned.
30 *
31 * JSON:
32 *
33 * When _application/json_ is accepted, connect will respond with
34 * an object in the form of `{ "error": error }`.
35 *
36 * HTML:
37 *
38 * When accepted connect will output a nice html stack trace.
39 *
40 * @return {Function}
41 * @api public
42 */
43
44exports = module.exports = function errorHandler(){
45 return function errorHandler(err, req, res, next){
46 if (err.status) res.statusCode = err.status;
47 if (res.statusCode < 400) res.statusCode = 500;
48 if ('test' != env) console.error(err.stack);
49 var accept = req.headers.accept || '';
50 // html
51 if (~accept.indexOf('html')) {
52 fs.readFile(__dirname + '/../public/style.css', 'utf8', function(e, style){
53 fs.readFile(__dirname + '/../public/error.html', 'utf8', function(e, html){
54 var stack = (err.stack || '')
55 .split('\n').slice(1)
56 .map(function(v){ return '<li>' + v + '</li>'; }).join('');
57 html = html
58 .replace('{style}', style)
59 .replace('{stack}', stack)
60 .replace('{title}', exports.title)
61 .replace('{statusCode}', res.statusCode)
62 .replace(/\{error\}/g, utils.escape(err.toString()));
63 res.setHeader('Content-Type', 'text/html; charset=utf-8');
64 res.end(html);
65 });
66 });
67 // json
68 } else if (~accept.indexOf('json')) {
69 var error = { message: err.message, stack: err.stack };
70 for (var prop in err) error[prop] = err[prop];
71 var json = JSON.stringify({ error: error });
72 res.setHeader('Content-Type', 'application/json');
73 res.end(json);
74 // plain text
75 } else {
76 res.writeHead(res.statusCode, { 'Content-Type': 'text/plain' });
77 res.end(err.stack);
78 }
79 };
80};
81
82/**
83 * Template title, framework authors may override this value.
84 */
85
86exports.title = 'Connect';