Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Make error message for ApiError more user-friendly #240

Merged
merged 4 commits into from
Jul 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion async-openai/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub enum OpenAIError {
#[error("http error: {0}")]
Reqwest(#[from] reqwest::Error),
/// OpenAI returns error object with details of API call failure
#[error("{:?}: {}", .0.r#type, .0.message)]
#[error("{0}")]
ApiError(ApiError),
/// Error when a response cannot be deserialized into a Rust type
#[error("failed to deserialize api response: {0}")]
Expand Down Expand Up @@ -36,6 +36,31 @@ pub struct ApiError {
pub code: Option<String>,
}

impl std::fmt::Display for ApiError {
/// If all fields are available, `ApiError` is formatted as:
/// `{type}: {message} (param: {param}) (code: {code})`
/// Otherwise, missing fields will be ignored.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut parts = Vec::new();

if let Some(r#type) = &self.r#type {
parts.push(format!("{}:", r#type));
}

parts.push(self.message.clone());

if let Some(param) = &self.param {
parts.push(format!("(param: {param})"));
}

if let Some(code) = &self.code {
parts.push(format!("(code: {code})"));
}

write!(f, "{}", parts.join(" "))
}
}

/// Wrapper to deserialize the error object nested in "error" JSON key
#[derive(Debug, Deserialize)]
pub(crate) struct WrappedError {
Expand Down