export function errorFromJson()

in packages/dubbo/src/protocol-triple/error-json.ts [31:83]


export function errorFromJson(
  jsonValue: JsonValue,
  metadata: HeadersInit | undefined,
  fallback: ConnectError
): ConnectError {
  if (metadata) {
    new Headers(metadata).forEach((value, key) =>
      fallback.metadata.append(key, value)
    );
  }
  if (
    typeof jsonValue !== "object" ||
    jsonValue == null ||
    Array.isArray(jsonValue) ||
    !("code" in jsonValue) ||
    typeof jsonValue.code !== "string"
  ) {
    throw fallback;
  }
  const code = codeFromString(jsonValue.code);
  if (code === undefined) {
    throw fallback;
  }
  const message = jsonValue.message;
  if (message != null && typeof message !== "string") {
    throw fallback;
  }
  const error = new ConnectError(message ?? "", code, metadata);
  if ("details" in jsonValue && Array.isArray(jsonValue.details)) {
    for (const detail of jsonValue.details) {
      if (
        detail === null ||
        typeof detail != "object" ||
        Array.isArray(detail) ||
        typeof detail.type != "string" ||
        typeof detail.value != "string" ||
        ("debug" in detail && typeof detail.debug != "object")
      ) {
        throw fallback;
      }
      try {
        error.details.push({
          type: detail.type,
          value: protoBase64.dec(detail.value),
          debug: detail.debug,
        });
      } catch (e) {
        throw fallback;
      }
    }
  }
  return error;
}