ZeroLeaks
Shield SDK

Errors

ShieldError, InjectionDetectedError, and LeakDetectedError. Error handling and try/catch patterns.

Errors

Shield defines three error classes for structured error handling. All extend ShieldError, which provides a code property for programmatic handling.

ShieldError

Base class for all Shield errors. Extends Error and adds a code string.

class ShieldError extends Error {
  readonly code: string;
  constructor(message: string, code: string);
}

InjectionDetectedError

Thrown when prompt injection is detected and onDetection is "block". Includes risk and categories for logging or alerting.

class InjectionDetectedError extends ShieldError {
  readonly risk: string;        // "low" | "medium" | "high" | "critical"
  readonly categories: string[]; // e.g. ["instruction_override", "role_hijack"]
  constructor(risk: string, categories: string[]);
  // code: "INJECTION_DETECTED"
}

LeakDetectedError

Thrown when output sanitization detects leaked system prompt fragments (if the provider or your code chooses to throw). Includes confidence and fragmentCount.

class LeakDetectedError extends ShieldError {
  readonly confidence: number;   // 0-1
  readonly fragmentCount: number;
  constructor(confidence: number, fragmentCount: number);
  // code: "LEAK_DETECTED"
}

Provider wrappers throw InjectionDetectedError when injection is detected and onDetection is "block". They throw LeakDetectedError when a leak is detected and throwOnLeak is true.

Example try/catch

import { shieldOpenAI } from "@zeroleaks/shield/openai";
import { InjectionDetectedError, LeakDetectedError } from "@zeroleaks/shield";

const client = shieldOpenAI(openai, {
  systemPrompt: "...",
  onDetection: "block",
  throwOnLeak: true,
});

try {
  const response = await client.chat.completions.create({
    model: "gpt-4o",
    messages: [{ role: "user", content: userInput }],
  });
  return response;
} catch (err) {
  if (err instanceof InjectionDetectedError) {
    console.log(err.risk, err.categories);
    return { error: "Invalid request", status: 400 };
  }
  if (err instanceof LeakDetectedError) {
    console.log(err.confidence, err.fragmentCount);
    return { error: "Output sanitization failed", status: 500 };
  }
  throw err;
}

On this page