Skip to main content

dynamo_protocols/
error.rs

1// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Error types for protocol type operations.
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug, thiserror::Error)]
8pub enum OpenAIError {
9    /// OpenAI returns error object with details of API call failure
10    #[error("{0}")]
11    ApiError(ApiError),
12    /// Error when a response cannot be deserialized into a Rust type
13    #[error("failed to deserialize api response: {0}")]
14    JSONDeserialize(serde_json::Error),
15    /// Error from client side validation
16    /// or when builder fails to build request before making API call
17    #[error("invalid args: {0}")]
18    InvalidArgument(String),
19}
20
21/// OpenAI API returns error object on failure
22#[derive(Debug, Serialize, Deserialize, Clone)]
23pub struct ApiError {
24    pub message: String,
25    pub r#type: Option<String>,
26    pub param: Option<String>,
27    pub code: Option<String>,
28}
29
30impl std::fmt::Display for ApiError {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        let mut parts = Vec::new();
33
34        if let Some(r#type) = &self.r#type {
35            parts.push(format!("{}:", r#type));
36        }
37
38        parts.push(self.message.clone());
39
40        if let Some(param) = &self.param {
41            parts.push(format!("(param: {param})"));
42        }
43
44        if let Some(code) = &self.code {
45            parts.push(format!("(code: {code})"));
46        }
47
48        write!(f, "{}", parts.join(" "))
49    }
50}
51
52/// Wrapper to deserialize the error object nested in "error" JSON key
53#[derive(Debug, Deserialize, Serialize)]
54pub struct WrappedError {
55    pub error: ApiError,
56}