text: module.exports = errorHandler;
  
  var domain = require('domain');
  
  function errorHandler (req, res, opts) {
    var loggerWorks = true;
  
    // Set default options where necessary.
    opts = opts || {};
  
    if (typeof opts.fatal === 'undefined')
      opts.fatal = true;
  
    opts.log = opts.log || console.error;
  
    opts.handler = opts.handler || function (req, res, err) {
      res.writeHead(500, {'Content-Type': 'text/plain'});
      res.end('Server error.\n');
    };
  
    // Handle errors.
    var dom = domain.create();
    dom.add(req);
    dom.add(res);
    dom.on('error', function (err) {
      delete err.domain;
  
      // Log the error.
      try {
        opts.log({err: err}, err.stack);
      } catch (e) {
  
        // Fall back to console.error.
        console.log({err: e}, e.stack);
  
        // Take note.
        loggerWorks = false;
      }
  
      try {
        var t = setTimeout(function () {
          dom.exit();
          dom.dispose();
          if (opts.fatal) process.exit(1);
        }, 1000);
        res.on('finish', function () {
          clearTimeout(t);
  
          // The response was not being sent over HTTPS when exiting too
          // soon; hence, process.nextTick(). req.client.server doesn't
          // work over HTTPS either, so we'll have to make do with
          // process.exit().
          process.nextTick(function () {
            dom.exit();
            dom.dispose();
            if (opts.fatal) process.exit(1);
          });
        });
  
        opts.handler(req, res, err);
      } catch (e) {
  
        // Something failed; log error.
        if (loggerWorks) {
          opts.log({err: e}, e.stack);
        } else {
          console.error(e, e.stack);
        }
  
        // Clean up.
        dom.exit();
        dom.dispose();
        if (opts.fatal) process.exit(1);
      }
    });
  
    dom.enter();
    process.nextTick(dom.exit);
  }