Skip to main content

objectiveai_sdk/error/
response_error.rs

1//! Core API error type.
2
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6/// A trait for errors that have an HTTP status code and optional message.
7pub trait StatusError {
8    /// Returns the HTTP status code associated with this error.
9    fn status(&self) -> u16;
10
11    /// Returns the error message, if any.
12    fn message(&self) -> Option<serde_json::Value>;
13}
14
15/// An error returned by the ObjectiveAI API.
16///
17/// This struct represents an API error response containing an HTTP status
18/// code and a message. The message can be any JSON value, allowing for
19/// both simple string errors and structured error objects.
20#[derive(
21    Debug,
22    Clone,
23    PartialEq,
24    Serialize,
25    Deserialize,
26    thiserror::Error,
27    JsonSchema,
28    arbitrary::Arbitrary,
29)]
30#[error("{}", &serde_json::to_string(self).unwrap_or_default())]
31#[schemars(rename = "error.ResponseError")]
32pub struct ResponseError {
33    /// The HTTP status code of the error response.
34    pub code: u16,
35    /// The error message or details as a JSON value.
36    #[arbitrary(with = crate::arbitrary_util::arbitrary_json_value)]
37    pub message: serde_json::Value,
38}
39
40impl StatusError for ResponseError {
41    fn status(&self) -> u16 {
42        self.code
43    }
44
45    fn message(&self) -> Option<serde_json::Value> {
46        Some(self.message.clone())
47    }
48}
49
50impl<T> From<&T> for ResponseError
51where
52    T: StatusError,
53{
54    fn from(error: &T) -> Self {
55        ResponseError {
56            code: error.status(),
57            message: error.message().unwrap_or_default(),
58        }
59    }
60}