Skip to main content Link Search Menu Expand Document (external link)

AiError.ts overview

The AiError module provides comprehensive error handling for AI operations.

This module defines a hierarchy of error types that can occur when working with AI services, including HTTP request/response errors, input/output validation errors, and general runtime errors. All errors follow Effect’s structured error patterns and provide detailed context for debugging.

Error Types

  • HttpRequestError: Errors occurring during HTTP request processing
  • HttpResponseError: Errors occurring during HTTP response processing
  • MalformedInput: Errors when input data doesn’t match expected format
  • MalformedOutput: Errors when output data can’t be parsed or validated
  • UnknownError: Catch-all for unexpected runtime errors

Example

import { AiError } from "@effect/ai"
import { Effect, Match } from "effect"

const handleAiError = Match.type<AiError.AiError>().pipe(
  Match.tag("HttpRequestError", (err) => Effect.logError(`Request failed: ${err.message}`)),
  Match.tag("HttpResponseError", (err) => Effect.logError(`Response error (${err.response.status}): ${err.message}`)),
  Match.tag("MalformedInput", (err) => Effect.logError(`Invalid input: ${err.message}`)),
  Match.tag("MalformedOutput", (err) => Effect.logError(`Invalid output: ${err.message}`)),
  Match.orElse((err) => Effect.logError(`Unknown error: ${err.message}`))
)

Example

import { AiError } from "@effect/ai"
import { Effect, Option } from "effect"

const aiOperation = Effect.gen(function* () {
  // Some AI operation that might fail
  return yield* new AiError.HttpRequestError({
    module: "OpenAI",
    method: "completion",
    reason: "Transport",
    request: {
      method: "POST",
      url: "https://api.openai.com/v1/completions",
      urlParams: [],
      hash: Option.none(),
      headers: { "Content-Type": "application/json" }
    }
  })
})

const program = aiOperation.pipe(
  Effect.catchTag("HttpRequestError", (error) => {
    console.log("Request failed:", error.message)
    return Effect.succeed("fallback response")
  })
)

Since v1.0.0


Exports Grouped by Category


Errors

HttpRequestError (class)

Error that occurs during HTTP request processing.

This error is raised when issues arise before receiving an HTTP response, such as network connectivity problems, request encoding issues, or invalid URLs.

Example

import { AiError } from "@effect/ai"
import { Effect } from "effect"

const handleNetworkError = Effect.gen(function* () {
  const error = new AiError.HttpRequestError({
    module: "OpenAI",
    method: "createCompletion",
    reason: "Transport",
    request: {
      method: "POST",
      url: "https://api.openai.com/v1/completions",
      urlParams: [],
      hash: Option.none(),
      headers: { "Content-Type": "application/json" }
    },
    description: "Connection timeout after 30 seconds"
  })

  console.log(error.message)
  // "Transport: Connection timeout after 30 seconds (POST https://api.openai.com/v1/completions)"
})

Signature

declare class HttpRequestError

Source

Since v1.0.0

fromRequestError (static method)

Creates an HttpRequestError from a platform HttpClientError.RequestError.

Example

import { AiError } from "@effect/ai"
import { HttpClientError } from "@effect/platform"
import { Option } from "effect"

declare const platformError: HttpClientError.RequestError

const aiError = AiError.HttpRequestError.fromRequestError({
  module: "ChatGPT",
  method: "sendMessage",
  error: platformError
})

Signature

declare const fromRequestError: ({
  error,
  ...params
}: {
  readonly module: string
  readonly method: string
  readonly error: HttpClientError.RequestError
}) => HttpRequestError

Source

Since v1.0.0

[TypeId] (property)

Signature

readonly [TypeId]: "~@effect/ai/AiError"

Source

Since v1.0.0

HttpResponseError (class)

Error that occurs during HTTP response processing.

This error is thrown when issues arise after receiving an HTTP response, such as unexpected status codes, response decoding failures, or empty response bodies.

Example

import { AiError } from "@effect/ai"
import { Option } from "effect"

const responseError = new AiError.HttpResponseError({
  module: "OpenAI",
  method: "createCompletion",
  reason: "StatusCode",
  request: {
    method: "POST",
    url: "https://api.openai.com/v1/completions",
    urlParams: [],
    hash: Option.none(),
    headers: { "Content-Type": "application/json" }
  },
  response: {
    status: 429,
    headers: { "X-RateLimit-Remaining": "0" }
  },
  description: "Rate limit exceeded"
})

console.log(responseError.message)
// "StatusCode: Rate limit exceeded (429 POST https://api.openai.com/v1/completions)"

Signature

declare class HttpResponseError

Source

Since v1.0.0

fromResponseError (static method)

Creates an HttpResponseError from a platform HttpClientError.ResponseError.

Example

import { AiError } from "@effect/ai"
import { Headers, HttpClientError } from "@effect/platform"
import { Option } from "effect"

declare const platformError: HttpClientError.ResponseError

const aiError = AiError.HttpResponseError.fromResponseError({
  module: "OpenAI",
  method: "completion",
  error: platformError
})

Signature

declare const fromResponseError: ({
  error,
  ...params
}: {
  readonly module: string
  readonly method: string
  readonly error: HttpClientError.ResponseError
}) => Effect.Effect<never, HttpResponseError>

Source

Since v1.0.0

[TypeId] (property)

Signature

readonly [TypeId]: "~@effect/ai/AiError"

Source

Since v1.0.0

MalformedInput (class)

Error thrown when input data doesn’t match the expected format or schema.

This error occurs when the data provided to an AI operation fails validation, is missing required fields, or doesn’t conform to the expected structure.

Example

import { AiError } from "@effect/ai"
import { Effect } from "effect"

const validateInput = (data: unknown) =>
  typeof data === "string" && data.length > 0
    ? Effect.succeed(data)
    : Effect.fail(
        new AiError.MalformedInput({
          module: "ChatBot",
          method: "processMessage",
          description: "Input must be a non-empty string"
        })
      )

const program = validateInput("").pipe(
  Effect.catchTag("MalformedInput", (error) => {
    console.log(`Input validation failed: ${error.description}`)
    return Effect.succeed("Please provide a valid message")
  })
)

Signature

declare class MalformedInput

Source

Since v1.0.0

[TypeId] (property)

Signature

readonly [TypeId]: "~@effect/ai/AiError"

Source

Since v1.0.0

MalformedOutput (class)

Error thrown when output data can’t be parsed or validated.

This error occurs when AI service responses don’t match the expected format, contain invalid data structures, or fail schema validation during parsing.

Example

import { AiError } from "@effect/ai"
import { Effect, Schema } from "effect"

const ResponseSchema = Schema.Struct({
  message: Schema.String,
  tokens: Schema.Number
})

const parseResponse = (data: unknown) =>
  Schema.decodeUnknown(ResponseSchema)(data).pipe(
    Effect.mapError(
      (parseError) =>
        new AiError.MalformedOutput({
          module: "OpenAI",
          method: "completion",
          description: "Response doesn't match expected schema",
          cause: parseError
        })
    )
  )

const program = parseResponse({ invalid: "data" }).pipe(
  Effect.catchTag("MalformedOutput", (error) => {
    console.log(`Parsing failed: ${error.description}`)
    return Effect.succeed({ message: "Error", tokens: 0 })
  })
)

Signature

declare class MalformedOutput

Source

Since v1.0.0

fromParseError (static method)

Creates a MalformedOutput error from a Schema ParseError.

Example

import { AiError } from "@effect/ai"
import { Effect, Schema } from "effect"

const UserSchema = Schema.Struct({
  name: Schema.String,
  age: Schema.Number
})

const parseUser = (data: unknown) =>
  Schema.decodeUnknown(UserSchema)(data).pipe(
    Effect.mapError((parseError) =>
      AiError.MalformedOutput.fromParseError({
        module: "UserService",
        method: "parseUserData",
        error: parseError
      })
    )
  )

Signature

declare const fromParseError: ({
  error,
  ...params
}: {
  readonly module: string
  readonly method: string
  readonly description?: string
  readonly error: ParseError
}) => MalformedOutput

Source

Since v1.0.0

[TypeId] (property)

Signature

readonly [TypeId]: "~@effect/ai/AiError"

Source

Since v1.0.0

UnknownError (class)

Catch-all error for unexpected runtime errors in AI operations.

This error is used when an unexpected exception occurs that doesn’t fit into the other specific error categories. It provides context about where the error occurred and preserves the original cause for debugging.

Example

import { AiError } from "@effect/ai"
import { Effect } from "effect"

const riskyOperation = () => {
  try {
    // Some operation that might throw
    throw new Error("Unexpected network issue")
  } catch (cause) {
    return Effect.fail(
      new AiError.UnknownError({
        module: "ChatService",
        method: "sendMessage",
        description: "An unexpected error occurred during message processing",
        cause
      })
    )
  }
}

const program = riskyOperation().pipe(
  Effect.catchTag("UnknownError", (error) => {
    console.log(error.message)
    // "ChatService.sendMessage: An unexpected error occurred during message processing"
    return Effect.succeed("Service temporarily unavailable")
  })
)

Signature

declare class UnknownError

Source

Since v1.0.0

[TypeId] (property)

Signature

readonly [TypeId]: "~@effect/ai/AiError"

Source

Since v1.0.0

Guards

isAiError

Type guard to check if a value is an AI error.

Example

import { AiError } from "@effect/ai"

const someError = new Error("generic error")
const aiError = new AiError.UnknownError({
  module: "Test",
  method: "example"
})

console.log(AiError.isAiError(someError)) // false
console.log(AiError.isAiError(aiError)) // true

Signature

declare const isAiError: (u: unknown) => u is AiError

Source

Since v1.0.0

Models

AiError (type alias)

Union type representing all possible AI operation errors.

This type encompasses all error cases that can occur during AI operations, providing a comprehensive error handling surface for applications.

Example

import { AiError } from "@effect/ai"
import { Effect, Match } from "effect"

const handleAnyAiError = Match.type<AiError.AiError>().pipe(
  Match.tag("HttpRequestError", (err) => `Network error: ${err.reason}`),
  Match.tag("HttpResponseError", (err) => `Server error: HTTP ${err.response.status}`),
  Match.tag("MalformedInput", (err) => `Invalid input: ${err.description || "Data validation failed"}`),
  Match.tag("MalformedOutput", (err) => `Invalid response: ${err.description || "Response parsing failed"}`),
  Match.orElse((err) => `Unknown error: ${err.message}`)
)

Signature

type AiError = HttpRequestError | HttpResponseError | MalformedInput | MalformedOutput | UnknownError

Source

Since v1.0.0

Schemas

AiError

Schema for validating and parsing AI errors.

This schema can be used to decode unknown values into properly typed AI errors, ensuring type safety when handling errors from external sources or serialized data.

Example

import { AiError } from "@effect/ai"
import { Schema, Effect } from "effect"

const parseAiError = (data: unknown) =>
  Schema.decodeUnknown(AiError.AiError)(data).pipe(
    Effect.map((error) => {
      console.log(`Parsed AI error: ${error._tag}`)
      return error
    }),
    Effect.catchAll(() =>
      Effect.succeed(
        new AiError.UnknownError({
          module: "Parser",
          method: "parseAiError",
          description: "Failed to parse error data"
        })
      )
    )
  )

Signature

declare const AiError: Schema.Union<
  [
    typeof HttpRequestError,
    typeof HttpResponseError,
    typeof MalformedInput,
    typeof MalformedOutput,
    typeof UnknownError
  ]
>

Source

Since v1.0.0

HttpRequestDetails

Schema for HTTP request details used in error reporting.

Captures comprehensive information about HTTP requests that failed, enabling detailed error analysis and debugging.

Example

import { AiError } from "@effect/ai"
import { Option } from "effect"

const requestDetails: typeof AiError.HttpRequestDetails.Type = {
  method: "POST",
  url: "https://api.openai.com/v1/completions",
  urlParams: [
    ["model", "gpt-4"],
    ["stream", "false"]
  ],
  hash: Option.some("#section1"),
  headers: { "Content-Type": "application/json" }
}

Signature

declare const HttpRequestDetails: Schema.Struct<{
  method: Schema.Literal<["GET", "POST", "PATCH", "PUT", "DELETE", "HEAD", "OPTIONS"]>
  url: typeof Schema.String
  urlParams: Schema.Array$<Schema.Tuple2<typeof Schema.String, typeof Schema.String>>
  hash: Schema.Option<typeof Schema.String>
  headers: Schema.Record$<typeof Schema.String, typeof Schema.String>
}>

Source

Since v1.0.0

HttpResponseDetails

Schema for HTTP response details used in error reporting.

Captures essential information about HTTP responses that caused errors, including status codes and headers for debugging purposes.

Example

import { AiError } from "@effect/ai"

const responseDetails: typeof AiError.HttpResponseDetails.Type = {
  status: 429,
  headers: {
    "Content-Type": "application/json",
    "X-RateLimit-Remaining": "0",
    "Retry-After": "60"
  }
}

Signature

declare const HttpResponseDetails: Schema.Struct<{
  status: typeof Schema.Number
  headers: Schema.Record$<typeof Schema.String, typeof Schema.String>
}>

Source

Since v1.0.0

Type Ids

TypeId

Unique identifier for AI errors.

Signature

declare const TypeId: "~@effect/ai/AiError"

Source

Since v1.0.0

TypeId (type alias)

Type-level representation of the AI error identifier.

Signature

type TypeId = typeof TypeId

Source

Since v1.0.0