Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

1.9 KB
Raw Blame
// Copyright 2026 The OpenSandbox Authors
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { SandboxApiException, SandboxError } from "@alibaba-group/opensandbox";

export function throwOnOpenApiFetchError(
  result: { error?: unknown; response: Response },
  fallbackMessage: string,
): void {
  // openapi-fetch leaves `error` unset (or an empty string) when an error
  // response has no body, so the status code must decide as well.
  if (!result.error && result.response.ok) return;

  const requestId = result.response.headers.get("x-request-id") ?? undefined;
  const status = (result.response as any).status ?? 0;

  const err = result.error as any;

  let rawFragment: string | undefined;
  if (typeof result.error === "string") {
    rawFragment = result.error;
  } else if (result.error && typeof result.error === "object") {
    try {
      rawFragment = JSON.stringify(result.error);
    } catch {
      rawFragment = undefined;
    }
  }

  const message =
    err?.message ??
    err?.error?.message ??
    (rawFragment && rawFragment.length > 0 ? rawFragment : fallbackMessage);

  const code = err?.code ?? err?.error?.code;

  throw new SandboxApiException({
    message,
    statusCode: status,
    requestId,
    error: code
      ? new SandboxError(String(code), message)
      : new SandboxError(SandboxError.UNEXPECTED_RESPONSE, message),
    rawBody: result.error,
  });
}