log error http response to telemetry
972554
public void logHttpRequestTelemetryEvent(
      String eventName,
      HttpRequestBase request,
      int injectSocketTimeout,
      AtomicBoolean canceling,
      boolean withoutCookies,
      boolean includeRetryParameters,
      boolean includeRequestGuid,
      CloseableHttpResponse response,
      final Exception savedEx,
      String breakRetryReason,
      long retryTimeout,
      int retryCount,
      String sqlState,
      int errorCode)
  {
    if (enabled)
    {
      TelemetryEvent.LogBuilder logBuilder = new TelemetryEvent.LogBuilder();
      JSONObject value = new JSONObject();
      value.put("request", request.toString());
      value.put("retryTimeout", retryTimeout);
      value.put("injectSocketTimeout", injectSocketTimeout);
      value.put("canceling", canceling == null ? "null" : canceling.get());
      value.put("withoutCookies", withoutCookies);
      value.put("includeRetryParameters", includeRetryParameters);
      value.put("includeRequestGuid", includeRequestGuid);
      value.put("breakRetryReason", breakRetryReason);
      value.put("retryTimeout", retryTimeout);
      value.put("retryCount", retryCount);
      value.put("sqlState", sqlState);
      value.put("errorCode", errorCode);
      int responseStatusCode = -1;
      if (response != null)
      {
        value.put("response", response.toString());
        value.put("responseStatusLine", response.getStatusLine().toString());
        if (response.getStatusLine() != null)
        {
          responseStatusCode = response.getStatusLine().getStatusCode();
          value.put("responseStatusCode", responseStatusCode);
        }
      }
      else
      {
        value.put("response", null);
      }
      if (savedEx != null)
      {
        value.put("exceptionMessage", savedEx.getLocalizedMessage());
        StringWriter sw = new StringWriter();
        savedEx.printStackTrace(new PrintWriter(sw));
        value.put("exceptionStackTrace", sw.toString());
      }
      TelemetryEvent log = logBuilder
          .withName(eventName)
          .withValue(value)
          .withTag("sqlState", sqlState)
          .withTag("errorCode", errorCode)
          .withTag("responseStatusCode", responseStatusCode)
          .build();
      this.add(log);
    }
  }
123069
function _logError($response, $status = -1)
    {
        if ($status == -1) {
            if (strlen($response) < 4) {
                return;
            }
            extract(unpack('Nstatus', $this->_string_shift($response, 4)));
        }

        $error = $this->status_codes[$status];

        if ($this->version > 2 || strlen($response) < 4) {
            extract(unpack('Nlength', $this->_string_shift($response, 4)));
            $this->sftp_errors[] = $error . ': ' . $this->_string_shift($response, $length);
        } else {
            $this->sftp_errors[] = $error;
        }
    }
135497
def error_response(
    error_type="Internal server error",
    error_text="",
    status=400,
    participant=None,
    simple=False,
    request_data="",
):
    """"""
    last_exception = sys.exc_info()
    if last_exception[0]:
        db.logger.error(
            "Failure for request: {!r}".format(dict(request.args)),
            exc_info=last_exception,
        )

    data = {"status": "error"}

    if simple:
        data["message"] = error_text
    else:
        data["html"] = (
            error_page(
                error_text=error_text,
                error_type=error_type,
                participant=participant,
                request_data=request_data,
            )
            .get_data()
            .decode("utf-8")
        )
    return Response(dumps(data), status=status, mimetype="application/json")
1059181
def _http_error_handler(http_error):
    ''' '''
    message = str(http_error)
    if http_error.respbody is not None:
        message += '\n' + http_error.respbody.decode('utf-8-sig')
    raise AzureHttpError(message, http_error.status)
636312
def log_request_fail(self, method, full_url, path, body, duration, status_code=None, response=None, exception=None):
        
        # do not log 404s on HEAD requests
        if method == 'HEAD' and status_code == 404:
            return
        logger.warning(
            '%s %s [status:%s request:%.3fs]', method, full_url,
            status_code or 'N/A', duration, exc_info=exception is not None
        )

        # body has already been serialized to utf-8, deserialize it for logging
        # TODO: find a better way to avoid (de)encoding the body back and forth
        if body:
            try:
                body = body.decode('utf-8', 'ignore')
            except AttributeError:
                pass

        logger.debug('> %s', body)

        self._log_trace(method, path, body, status_code, response, duration)

        if response is not None:
            logger.debug('< %s', response)
860521
def _handle_http_errors(response):
    
    code = response.status_code
    if 200 <= code < 400:
        return response
    elif code in (403, 404):
        raise {403: _ObjectPermissionError,
               404: _ObjectNotFoundError}[code](response.reason)
    response.raise_for_status()
122358
def http_reply(self):
        """"""
        data = {
            'status': self.status,
            'error': self.code.upper(),
            'error_description': str(self)
        }

        if self.error_caught:
            data['error_caught'] = pformat(self.error_caught)

        if self.error_id:
            data['error_id'] = self.error_id

        if self.user_message:
            data['user_message'] = self.user_message

        r = jsonify(data)
        r.status_code = self.status

        if str(self.status) != "200":
            log.warn("ERROR: caught error %s %s [%s]" % (self.status, self.code, str(self)))

        return r
1250232
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
    ByteBuf content = Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8);

    ctx.write(response);
    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(content).addListener(ChannelFutureListener.CLOSE);
  }
75133
function error(err, req, res, next) {
  // log it
  if (!test) console.error(err.stack);

  // respond with 500 "Internal Server Error".
  res.status(500);
  res.send('Internal Server Error');
}
342551
def _check_error_response(response, query):
        
        if "error" in response:
            http_error = ["HTTP request timed out.", "Pool queue is full"]
            geo_error = [
                "Page coordinates unknown.",
                "One of the parameters gscoord, gspage, gsbbox is required",
                "Invalid coordinate provided",
            ]
            err = response["error"]["info"]
            if err in http_error:
                raise HTTPTimeoutError(query)
            elif err in geo_error:
                raise MediaWikiGeoCoordError(err)
            else:
                raise MediaWikiException(err)
670391
function logError (failure, index) {
  index = index + 1

  if (index > 1) {
    log('\n\n')
  }

  log('  ' + index + ') ' + failure.description + ': ')

  if (failure.environment) {
    log(('(' + failure.environment + ')').grey)
  }

  log('\n\n')

  // Log the actual error message / stack trace / diffs
  var intend = 4 + String(index).length
  var error = formatError(failure.error, intend)

  if (!_empty(error.message)) {
    log(error.message + '\n')
  }

  if (!_empty(error.stack)) {
    log('\n' + error.stack.grey + '\n')
  }
}
414173
public static void logResponse(
            Logger logger, RequestLog log, LogLevel requestLogLevel,
            Function<? super HttpHeaders, ? extends HttpHeaders> requestHeadersSanitizer,
            Function<Object, ?> requestContentSanitizer,
            Function<? super HttpHeaders, ? extends HttpHeaders> requestTrailersSanitizer,
            LogLevel successfulResponseLogLevel,
            LogLevel failedResponseLogLevel,
            Function<? super HttpHeaders, ? extends HttpHeaders> responseHeadersSanitizer,
            Function<Object, ?> responseContentSanitizer,
            Function<? super HttpHeaders, ? extends HttpHeaders> responseTrailersSanitizer,
            Function<? super Throwable, ? extends Throwable> responseCauseSanitizer) {

        final Throwable responseCause = log.responseCause();
        final LogLevel level = responseCause == null ? successfulResponseLogLevel
                                                     : failedResponseLogLevel;
        if (level.isEnabled(logger)) {
            final String responseStr = log.toStringResponseOnly(responseHeadersSanitizer,
                                                                responseContentSanitizer,
                                                                responseTrailersSanitizer);
            if (responseCause == null) {
                level.log(logger, RESPONSE_FORMAT, responseStr);
            } else {
                if (!requestLogLevel.isEnabled(logger)) {
                    // Request wasn't logged but this is an unsuccessful response, log the request too to help
                    // debugging.
                    level.log(logger, REQUEST_FORMAT, log.toStringRequestOnly(requestHeadersSanitizer,
                                                                              requestContentSanitizer,
                                                                              requestTrailersSanitizer));
                }

                final Throwable sanitizedResponseCause = responseCauseSanitizer.apply(responseCause);
                if (sanitizedResponseCause != null) {
                    level.log(logger, RESPONSE_FORMAT, responseStr, sanitizedResponseCause);
                } else {
                    level.log(logger, RESPONSE_FORMAT, responseStr);
                }
            }
        }
    }
1118976
def send_errors_to_logging():
    """"""
    error_output = vtk.vtkStringOutputWindow()
    error_win = vtk.vtkOutputWindow()
    error_win.SetInstance(error_output)
    obs = Observer()
    return obs.observe(error_output)
1057312
function _logProgress(req) {
  req.on('response', function(resp) {
    var len = parseInt(resp.headers['content-length'], 10),
      bar = new ProgressBar('[:bar]', {
        complete: '=',
        incomplete: ' ',
        total: len,
        width: 100, // just use 100
      });

    req.on('data', function(chunk) {
      bar.tick(chunk.length);
    });
  });

  req.on('error', function(err) {
    console.log(err);
    _log('error', 'failed to download node sources,');
    process.exit(1);
  });

  return req;
}
1900
async def async_get_sensor_log(self, index: int) -> Optional[SensorLogResponse]:
        

        response = await self._protocol.async_execute(
            GetSensorLogCommand(index))
        if isinstance(response, SensorLogResponse):
            return response
        return None
657217
def httperror_handler(error):
    
    status_code = error.status_code or 500
    output = {
        'code': status_code,
        'message': error.body or UNEXPECTED_ERROR,
        'reason': bottle.HTTP_CODES.get(status_code) or None,
    }
    if bottle.DEBUG:
        LOG.warning("Debug-mode server is returning traceback and error "
                    "details in the response with a %s status.",
                    error.status_code)
        if error.exception:
            output['exception'] = repr(error.exception)
        else:
            if any(sys.exc_info()):
                output['exception'] = repr(sys.exc_info()[1])
            else:
                output['exception'] = None

        if error.traceback:
            output['traceback'] = error.traceback
        else:
            if any(sys.exc_info()):
                # Otherwise, format_exc() returns "None\n"
                # which is pretty silly.
                output['traceback'] = traceback.format_exc()
            else:
                output['traceback'] = None

    # overwrite previous body attr with json
    if isinstance(output['message'], bytes):
        output['message'] = output['message'].decode(
            'utf-8', errors='replace')

    # Default type and writer to json.
    accept = bottle.request.get_header('accept') or 'application/json'
    writer = functools.partial(
        json.dumps, sort_keys=True, indent=4)
    error.set_header('Content-Type', 'application/json')
    if 'json' not in accept:
        if 'yaml' in accept:
            if not yaml:
                LOG.warning("Yaml requested but pyyaml is not installed.")
            else:
                error.set_header('Content-Type', 'application/x-yaml')
                writer = functools.partial(
                    yaml.safe_dump,
                    default_flow_style=False,
                    indent=4)
            # html could be added here.

    error.body = [writer(output).encode('utf8')]
    return error.body
794732
def _server_error_message(url, message):
    """"""
    msg = _error_message.format(url=url, message=message)
    log.error(msg)
    return msg