142
St
startsInvasion / files
startsInvasion / libs / node_modules / reqwest / build / connect / lib / middleware / errorHandler.js
2.8 KB
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 , url = require('url') 14 , fs = require('fs'); 15 16/** 17 * Flexible error handler, providing (_optional_) stack traces 18 * and error message responses for requests accepting text, html, 19 * or json. 20 * 21 * Options: 22 * 23 * - `showStack`, `stack` respond with both the error message and stack trace. Defaults to `false` 24 * - `showMessage`, `message`, respond with the exception message only. Defaults to `false` 25 * - `dumpExceptions`, `dump`, dump exceptions to stderr (without terminating the process). Defaults to `false` 26 * 27 * Text: 28 * 29 * By default, and when _text/plain_ is accepted a simple stack trace 30 * or error message will be returned. 31 * 32 * JSON: 33 * 34 * When _application/json_ is accepted, connect will respond with 35 * an object in the form of `{ "error": error }`. 36 * 37 * HTML: 38 * 39 * When accepted connect will output a nice html stack trace. 40 * 41 * @param {Object} options 42 * @return {Function} 43 * @api public 44 */ 45 46exports = module.exports = function errorHandler(options){ 47 options = options || {}; 48 49 // defaults 50 var showStack = options.showStack || options.stack 51 , showMessage = options.showMessage || options.message 52 , dumpExceptions = options.dumpExceptions || options.dump 53 , formatUrl = options.formatUrl; 54 55 return function errorHandler(err, req, res, next){ 56 res.statusCode = 500; 57 if (dumpExceptions) console.error(err.stack); 58 if (showStack) { 59 var accept = req.headers.accept || ''; 60 // html 61 if (~accept.indexOf('html')) { 62 fs.readFile(__dirname + '/../public/style.css', 'utf8', function(e, style){ 63 fs.readFile(__dirname + '/../public/error.html', 'utf8', function(e, html){ 64 var stack = (err.stack || '') 65 .split('\n').slice(1) 66 .map(function(v){ return '<li>' + v + '</li>'; }).join(''); 67 html = html 68 .replace('{style}', style) 69 .replace('{stack}', stack) 70 .replace('{title}', exports.title) 71 .replace(/\{error\}/g, utils.escape(err.toString())); 72 res.setHeader('Content-Type', 'text/html'); 73 res.end(html); 74 }); 75 }); 76 // json 77 } else if (~accept.indexOf('json')) { 78 var json = JSON.stringify({ error: err }); 79 res.setHeader('Content-Type', 'application/json'); 80 res.end(json); 81 // plain text 82 } else { 83 res.writeHead(500, { 'Content-Type': 'text/plain' }); 84 res.end(err.stack); 85 } 86 } else { 87 var body = showMessage 88 ? err.toString() 89 : 'Internal Server Error'; 90 res.setHeader('Content-Type', 'text/plain'); 91 res.end(body); 92 } 93 }; 94}; 95 96/** 97 * Template title. 98 */ 99 100exports.title = 'Connect';