菜单
文档breadcrumb arrow Grafana k6breadcrumb arrow 示例breadcrumb arrow 错误处理程序
开源

错误处理程序

从应用程序后端遇到错误时,通常需要收集额外的错误信息,例如错误消息、追踪数据或请求和响应正文。最初的建议是利用您的可观测性解决方案来查找这些错误。然而,直接在 k6 中捕获错误详细信息对于故障排除也很有用。

在 k6 中,有两种常见的方法来存储额外的错误信息

决定存储哪些错误数据时,考虑它是通用错误还是特定错误,并注意高负载测试可能会生成大量错误数据。

下面是一个使用 ErrorHandler 类记录错误信息的示例。它接受一个回调,该回调指示如何记录错误。示例为前面提到的两种选项提供了说明:控制台日志和自定义指标。

JavaScript
import http from 'k6/http';
import { check } from 'k6';

// General error handler to log error details.
class ErrorHandler {
  // Instruct the error handler how to log errors
  constructor(logErrorDetails) {
    this.logErrorDetails = logErrorDetails;
  }

  // Logs response error details if isError is true.
  logError(isError, res, tags = {}) {
    if (!isError) return;

    // the Traceparent header is a W3C Trace Context
    const traceparentHeader = res.request.headers['Traceparent'];

    // Add any other useful information
    const errorData = Object.assign(
      {
        url: res.url,
        status: res.status,
        error_code: res.error_code,
        traceparent: traceparentHeader && traceparentHeader.toString(),
      },
      tags
    );
    this.logErrorDetails(errorData);
  }
}

// Set up the error handler to log errors to the console
const errorHandler = new ErrorHandler((error) => {
  console.error(error);
});

/* Alternatively, you may log errors using a custom metric or any other option.
const errors = new CounterMetric('errors');
const errorHandler = new ErrorHandler((error) => {errors.add(1, error);});
*/

// Basic example to demonstrate the error handler
export default function () {
  let res, checkStatus;

  res = http.get('https://httpbin.org/status/200');
  checkStatus = check(res, { 'status is 200': (res) => res.status === 200 });
  errorHandler.logError(!checkStatus, res);

  res = http.get('https://httpbin.org/status/300');
  checkStatus = check(res, { 'status is 200': (res) => res.status === 200 });
  errorHandler.logError(!checkStatus, res);
}