Override the next() error/passthrough handler to clean up before leaving. This way, the timer doesn't go off / the subscriber doesn't handle messages after we've sent the response, and the server doesn't crash as a result.
421190
function next(err) {
      return finish(function (finishErr) {
        if (err) return topnext(err);
        else if (finishErr) return topnext(finishErr);
        else return topnext();
      });
    }
863864
function (event) {
                // Do nothing if the request has been cancelled.
                if (cancelled) {
                    return;
                }
                // Cleanup the page.
                cleanup();
                // Check whether the response callback has run.
                if (!finished) {
                    // It hasn't, something went wrong with the request. Return an error via
                    // the Observable error path. All JSONP errors have status 0.
                    observer.error(new HttpErrorResponse({
                        url: url,
                        status: 0,
                        statusText: 'JSONP Error',
                        error: new Error(JSONP_ERR_NO_CALLBACK),
                    }));
                    return;
                }
                // Success. body either contains the response body or null if none was
                // returned.
                observer.next(new HttpResponse({
                    body: body,
                    status: 200,
                    statusText: 'OK', url: url,
                }));
                // Complete the stream, the response is over.
                observer.complete();
            }
734429
function responseHandler (res, next) {
  return function (err, message) {
    if (err || !message) {
      next(err);
    } else {
      res.send(message);
    }
  }
}
294818
function handleRequestError(eventTarget, type) {
  readyStateChange(eventTarget, states.DONE);

  dispatchProgressEvent(eventTarget, {
    type: 'progress',
    total: 0,
    loaded: 0,
    lengthComputable: false
  });

  dispatchProgressEvent(eventTarget, {
    type: type,
    total: 0,
    loaded: 0,
    lengthComputable: false
  });

  dispatchProgressEvent(eventTarget, {
    type: 'loadend',
    total: 0,
    loaded: 0,
    lengthComputable: false
  });
}
1284650
def _method_error_handler(self, response: Dict[str, Any]):
        
        exp = response.get('MESSAGE')
        code = response.get("CODE")
        ID = exp.get("ID")
        e = abort(code, ID=ID, message=exp.get('MESSAGE'))
        self.tasks[ID].set_exception(e)
        return True
316775
@Override
    public IPromise<T> onError(Consumer errorHandler) {
        return then( (r,e) -> {
            if ( e != null && e != Timeout.INSTANCE) {
                errorHandler.accept(e);
            }
        });
    }
1022474
function onClientTimeoutPostRequestHandler (ctx, err) {
  if (err) {
    let error = null;
    if (err instanceof SuperError) {
      error = err.rootCause || err.cause || err;
    } else {
      error = err;
    }

    let internalError = new Errors.MostlyError(Constants.EXTENSION_ERROR).causedBy(err);
    ctx.log.error(internalError);

    ctx._response.error = error;
    ctx.emit('clientResponseError', error);
  }

  try {
    ctx._execute(ctx._response.error);
  } catch(err) {
    let error = null;
    if (err instanceof SuperError) {
      error = err.rootCause || err.cause || err;
    } else {
      error = err;
    }

    let internalError = new Errors.FatalError(Constants.FATAL_ERROR, ctx.errorDetails).causedBy(err);
    ctx.log.fatal(internalError);

    ctx.emit('clientResponseError', error);

    // let it crash
    if (ctx._config.crashOnFatal) {
      ctx.fatal();
    }
  }
}
1201888
def _wrap_callback_errors(callback, message):
    
    try:
        callback(message)
    except Exception:
        # Note: the likelihood of this failing is extremely low. This just adds
        # a message to a queue, so if this doesn't work the world is in an
        # unrecoverable state and this thread should just bail.
        _LOGGER.exception(
            "Top-level exception occurred in callback while processing a " "message"
        )
        message.nack()
248882
function commonErrorHandler(err, req, res, next) { // jshint ignore:line

  debug(err);

  // if we got here without an error, it's a 404 case
  if (!err) {
    err = new NotFoundError();
  }

  // here we've got an error, it could be a different one than
  // the one we've constructed, so provide defaults to be safe
  err.message = err.message || 'Internal Server Error';

  res
    .status(err.code || err.statusCode || 500)
    .type('application/json')
    .send(stringify(err));
}
255367
function handlePreResponseError(server) {
        server.ext('onPreResponse', function (request, reply) {
            var response = request.response;
            var originalResponse = response;
            var msg;

            // No error, keep going with the reply as normal
            if (!response.isBoom) { reply.continue(); return; }

            // we need to convert to AppError if it is not already
            if (!(response instanceof AppError)) {
                msg = response.message || (response + '');

                // if legit 404 be sure to use that code (happens with not found in /dist on local)
                if (msg.indexOf('404:') >= 0 ||
                    (response.output && response.output.payload &&
                    response.output.payload.statusCode === 404)) {

                    response = new AppError({
                        code: 'not_found',
                        msg: 'The resource ' + request.url.path + ' was not found'
                    });
                }
                else {
                    msg = response.message || (response + '');
                    if (response.data) { msg += ' : ' + response.data; }

                    log.info(msg);

                    response = new AppError({
                        code: response.code || 'api_error',
                        msg: msg,
                        err: response
                    });
                }
            }

            var code = response.code || 'unknown_error';
            var err = errorDecoder[code] || errorDecoder['unknown_error'];
            var url = request.path;

            if (err.httpErrorCode === 404) {
                trackingService.pageNotFound({
                    caller: request.caller,
                    url: routeHelper.getBaseUrl(request.app.name) + url
                });
            }
            else {
                log.error(request.method + ' ' + url + ' (' + err.friendlyMessage + ')',
                    { err: originalResponse }   );
            }

            //TODO: this hack sucks, but needed quick way to display error page; do better!
            if (pancakes.getContainer() === 'webserver') {

                // hack fix for issue when error on trust site
                if (request.app && request.app.name === 'trust') {
                    reply().redirect(routeHelper.getBaseUrl('contact') + '?notify=loginFailure');
                }
                // else show error pages
                else {
                    var errUrl = err.httpErrorCode === 404 ? '/error404' : '/error500';
                    pancakes.processRoute({ request: request, reply: reply, urlOverride: errUrl, returnCode: err.httpErrorCode });
                }
            }
            else {
                reply(Boom.create(err.httpErrorCode, err.friendlyMessage));
            }
        });
    }
264323
function handler(responseCode, data, ioArgs) {
                    that.xhr = ioArgs.xhr;
                    that.statusCode = that.xhr && !that.xhr.timedOut && that.xhr.status || 0;
                    if (that.canceled) {
                        logger.debug("Request [" + that.id + "] was canceled, not calling handler");
                    } else {
                        that.pending = false;
                        that.complete = true;
                        paramHandler(responseCode, data, ioArgs);
                    }
                }
522792
private void serveError(Status status, ErrorMessage.FailureReason reason, RequestHandler requestHandler) throws IOException {
    this.serveError(status, reason.getMessage(), requestHandler);
  }
223531
function done(error) {
      global.clearTimeout(timer);
      eventLoop.removeListener('tick', ontick);
      eventLoop.removeListener('idle', done);
      eventLoop.browser.removeListener('error', done);

      --eventLoop.waiting;
      try {
        callback(error);
      } catch (error) {
        // If callback makes an assertion that fails, we end here.
        // If we throw error synchronously, it gets swallowed.
        setImmediate(function() {
          throw error;
        });
      }
    }
1089148
public static void sendError( String messageKey, Throwable cause, ServletRequest request,
                                  HttpServletResponse response, Object[] messageArgs )
            throws IOException
    {
        // TODO: the following null check will be unnecessary once the deprecated
        // FlowController.sendError(String, HttpServletResponse) is removed.
        boolean avoidDirectResponseOutput = request != null ? avoidDirectResponseOutput( request ) : false;
        sendError( messageKey, messageArgs, request, response, cause, avoidDirectResponseOutput );
    }
149524
function handlePushError(pushError, pushHandler) {
    return Platform.async(function(callback) {
        callback();
    })().then(function() {
        
        if (pushError.isConflict()) {
            if (pushHandler && pushHandler.onConflict) {
                // NOTE: value of server record will not be available in case of 409.
                return pushHandler.onConflict(pushError);
            }
        } else if (pushHandler && pushHandler.onError) {
            return pushHandler.onError(pushError);
        }

    }).then(undefined, function(error) {
        // Set isHandled to false even if the user has set it to handled if the onConflict / onError failed 
        pushError.isHandled = false;
    });
}
1235368
function logError(message, err, context, event) {
  var current_err = err;
  while (current_err) {
    var next_err = current_err._previous;
    delete current_err._previous;
    if (current_err.stack) {
      console.error(current_err.stack);
    } else {
      console.error(current_err);
    }
    current_err = next_err;
  }
  // TODO add cli options for logging out context and event as well
}
999740
function errorAndExit(msg, logMe) {
  // @todo Only trigger if `verbosity > 1`
  if (logMe) {
    // Adding some empty lines before error message for readability
    console.log();
    console.log();
    console.log(logMe);
  }
  error(`Error: ${msg}`);

  // There's a few ways to handle exiting

  // This is suggested and it's nice b/c it let's I/O finish up, but if an error happens on a watch task, it doesn't exit, b/c this will exit once the event loop is empty.
  // process.exitCode = 1;

  // This stops everything instantly and guarantees a killed program, but there's comments on the InterWebs about how it can be bad b/c I/O (like file writes) might not be done yet. I also have suspicions that this can lead to child processes never getting killed and running indefinitely - perhaps what leads to ports not being available
  // process.exit(1);

  // From docs for `process.nextTick` : "Once the current turn of the event loop turn runs to completion, all callbacks currently in the next tick queue will be called. This is not a simple alias to setTimeout(fn, 0). It is much more efficient. It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop."
  // This exits during watches correctly, and I *think* it'll let the I/O finish, but I'm not 100%
  process.nextTick(() => {
    process.exit(1);
  });
}