Skip to main content

switchyard_translation/
error.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Error types for request, response, and streaming translation.
5
6use thiserror::Error;
7
8use crate::format::FormatId;
9
10/// Result alias for translation operations.
11pub type Result<T> = std::result::Result<T, TranslationError>;
12
13/// Failures that can occur while decoding, encoding, or enforcing policy.
14#[derive(Debug, Error)]
15pub enum TranslationError {
16    #[error("invalid JSON: {0}")]
17    InvalidJson(#[from] serde_json::Error),
18
19    #[error("expected {expected} at {path}")]
20    InvalidType {
21        path: String,
22        expected: &'static str,
23    },
24
25    #[error("translation from {from} to {to} is not supported")]
26    UnsupportedTranslation { from: FormatId, to: FormatId },
27
28    #[error("lossy conversion rejected: {0}")]
29    LossyConversion(String),
30
31    #[error("invalid value at {path}: {message}")]
32    InvalidValue { path: String, message: String },
33
34    /// The response body reports a failed generation, such as OpenAI Responses
35    /// `status: "failed"`. `error` contains the provider's error object or a
36    /// message explaining that the provider supplied no error details.
37    #[error("upstream reported a failed response: {error}")]
38    UpstreamFailure { error: serde_json::Value },
39    #[error("{0}")]
40    Other(String),
41}
42
43impl TranslationError {
44    /// Returns the stable variant name for FFI and language-binding errors.
45    pub const fn kind(&self) -> &'static str {
46        match self {
47            Self::InvalidJson(_) => "InvalidJson",
48            Self::InvalidType { .. } => "InvalidType",
49            Self::UnsupportedTranslation { .. } => "UnsupportedTranslation",
50            Self::LossyConversion(_) => "LossyConversion",
51            Self::InvalidValue { .. } => "InvalidValue",
52            Self::UpstreamFailure { .. } => "UpstreamFailure",
53            Self::Other(_) => "Other",
54        }
55    }
56
57    /// Builds an [`TranslationError::InvalidValue`] for an unsupported message
58    /// role. A transparent router must reject the same payloads the upstream
59    /// provider would: an unknown role string (e.g. `"api"`) should surface as
60    /// an `invalid_value`-style error rather than being silently coerced to
61    /// `user`. `path` is a JSON-path pointer to the offending field so the
62    /// error reads like a provider validation error.
63    pub fn unsupported_role(path: impl Into<String>, value: &str) -> Self {
64        Self::InvalidValue {
65            path: path.into(),
66            message: format!(
67                "Invalid value: {value:?}. Supported message roles are \
68                 system, developer, user, assistant, tool."
69            ),
70        }
71    }
72}