openrouter_rs/
utils.rs

1use crate::{api::errors::ApiErrorResponse, error::OpenRouterError};
2use surf::Response;
3
4#[macro_export]
5macro_rules! setter {
6    ($name:ident, $type:ty) => {
7        pub fn $name(mut self, value: $type) -> Self {
8            self.$name = Some(value);
9            self
10        }
11    };
12}
13
14pub async fn handle_error(mut response: Response) -> Result<(), OpenRouterError> {
15    let status = response.status();
16    let text = response
17        .body_string()
18        .await
19        .unwrap_or_else(|_| "Failed to read response text".to_string());
20    let api_error_response: Result<ApiErrorResponse, _> = serde_json::from_str(&text);
21
22    if let Ok(api_error_response) = api_error_response {
23        Err(OpenRouterError::from(api_error_response))
24    } else {
25        Err(OpenRouterError::ApiError {
26            code: status,
27            message: text,
28        })
29    }
30}