Skip to main content

systemprompt_models/api/errors/
extension.rs

1//! Rendering an [`ExtensionError`] as an [`ApiError`].
2//!
3//! Copyright (c) systemprompt.io — Business Source License 1.1.
4//! See <https://systemprompt.io> for licensing details.
5
6use systemprompt_traits::ExtensionError;
7
8use super::{ApiError, ErrorCode};
9
10const EXTENSION_FAILURE: &str = "Extension operation failed";
11
12impl ApiError {
13    pub fn from_extension<E: ExtensionError>(err: E) -> Self {
14        let code = match err.status().as_u16() {
15            400 => ErrorCode::BadRequest,
16            401 => ErrorCode::Unauthorized,
17            403 => ErrorCode::Forbidden,
18            404 => ErrorCode::NotFound,
19            409 => ErrorCode::ConflictError,
20            422 => ErrorCode::ValidationError,
21            429 => ErrorCode::RateLimited,
22            503 => ErrorCode::ServiceUnavailable,
23            status if status >= 500 => ErrorCode::InternalError,
24            _ => ErrorCode::BadRequest,
25        };
26        let key = err.code();
27        if code.is_server_error() {
28            return Self::new(code, EXTENSION_FAILURE)
29                .with_error_key(key)
30                .with_source(err);
31        }
32        Self::new(code, err.user_message())
33            .with_error_key(key)
34            .with_source(err)
35    }
36}