Error Handling
Handle API errors, empty responses, and other failure modes.
SpeechSDK provides typed error classes for common failure modes.
Error Classes
import {
generateSpeech,
ApiError,
NoSpeechGeneratedError,
SpeechSDKError,
} from "@speech-sdk/core"| Error | When |
|---|---|
ApiError | Provider API returns a non-2xx response |
NoSpeechGeneratedError | Provider returned empty audio data |
SpeechSDKError | Base class for all SDK errors |
Catching Errors
import { generateSpeech, ApiError, SpeechSDKError } from "@speech-sdk/core"
try {
const result = await generateSpeech({
model: "openai/gpt-4o-mini-tts",
text: "Hello!",
voice: "alloy",
})
} catch (error) {
if (error instanceof ApiError) {
console.log(error.statusCode) // 401
console.log(error.model) // "openai/gpt-4o-mini-tts"
console.log(error.responseBody) // raw response from the API
} else if (error instanceof SpeechSDKError) {
console.log(error.message)
}
}ApiError
Thrown when the provider returns a non-2xx HTTP status. Contains details about what went wrong:
class ApiError extends SpeechSDKError {
readonly statusCode: number // HTTP status code
readonly responseBody?: unknown // Raw response body
readonly model: string // Model string that was used
}Common status codes:
401— Invalid or missing API key403— Insufficient permissions429— Rate limited500— Provider server error (will be retried)
NoSpeechGeneratedError
Thrown when the provider returns a successful response but the audio data is empty:
import { NoSpeechGeneratedError } from '@speech-sdk/core';
try {
const result = await generateSpeech({ ... });
} catch (error) {
if (error instanceof NoSpeechGeneratedError) {
// Provider returned no audio — try a different model or voice
}
}Retries
SpeechSDK automatically retries on 5xx errors and network failures with exponential backoff. 4xx errors (like authentication failures) are not retried. Default: 2 retries.
// Increase retries for unreliable connections
const result = await generateSpeech({
model: "openai/gpt-4o-mini-tts",
text: "Hello!",
voice: "alloy",
maxRetries: 5,
})// Disable retries
const result = await generateSpeech({
model: "openai/gpt-4o-mini-tts",
text: "Hello!",
voice: "alloy",
maxRetries: 0,
})