3 * Connect - errorHandler
4 * Copyright(c) 2010 Sencha Inc.
5 * Copyright(c) 2011 TJ Holowaychuk
10 * Module dependencies.
13 var utils = require('../utils')
14 , url = require('url')
18 * Flexible error handler, providing (_optional_) stack traces
19 * and error message responses for requests accepting text, html,
24 * - `showStack`, `stack` respond with both the error message and stack trace. Defaults to `false`
25 * - `showMessage`, `message`, respond with the exception message only. Defaults to `false`
26 * - `dumpExceptions`, `dump`, dump exceptions to stderr (without terminating the process). Defaults to `false`
30 * By default, and when _text/plain_ is accepted a simple stack trace
31 * or error message will be returned.
35 * When _application/json_ is accepted, connect will respond with
36 * an object in the form of `{ "error": error }`.
40 * When accepted connect will output a nice html stack trace.
42 * @param {Object} options
47 exports = module.exports = function errorHandler(options){
48 options = options || {};
51 var showStack = options.showStack || options.stack
52 , showMessage = options.showMessage || options.message
53 , dumpExceptions = options.dumpExceptions || options.dump
54 , formatUrl = options.formatUrl;
56 return function errorHandler(err, req, res, next){
58 if (dumpExceptions) console.error(err.stack);
60 var accept = req.headers.accept || '';
62 if (~accept.indexOf('html')) {
63 fs.readFile(__dirname + '/../public/style.css', 'utf8', function(e, style){
64 fs.readFile(__dirname + '/../public/error.html', 'utf8', function(e, html){
67 .map(function(v){ return '<li>' + v + '</li>'; }).join('');
69 .replace('{style}', style)
70 .replace('{stack}', stack)
71 .replace('{title}', exports.title)
72 .replace(/\{error\}/g, utils.escape(err.toString()));
73 res.setHeader('Content-Type', 'text/html');
78 } else if (~accept.indexOf('json')) {
79 var json = JSON.stringify({ error: err });
80 res.setHeader('Content-Type', 'application/json');
84 res.writeHead(500, { 'Content-Type': 'text/plain' });
88 var body = showMessage
90 : 'Internal Server Error';
91 res.setHeader('Content-Type', 'text/plain');
101 exports.title = 'Connect';