replicate_rs/
errors.rs

1use reqwest::StatusCode;
2use serde::Deserialize;
3use std::fmt;
4use thiserror::Error;
5
6#[derive(Debug, Clone, Error)]
7pub enum ReplicateError {
8    MissingCredentials(String),
9    InvalidCredentials(String),
10    PaymentNeeded(String),
11    SerializationError(String),
12    ClientError(String),
13    InvalidRequest(String),
14    Misc(String),
15}
16
17impl fmt::Display for ReplicateError {
18    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
19        match self {
20            ReplicateError::MissingCredentials(message)
21            | ReplicateError::PaymentNeeded(message)
22            | ReplicateError::ClientError(message)
23            | ReplicateError::Misc(message)
24            | ReplicateError::SerializationError(message) => {
25                write!(f, "{message}")
26            }
27            _ => {
28                write!(f, "unknown replicate error")
29            }
30        }
31    }
32}
33
34#[derive(Deserialize)]
35struct ErrorData {
36    title: String,
37    detail: String,
38}
39
40/// Result Alias for Replicate Output and Errors
41pub type ReplicateResult<T> = std::result::Result<T, ReplicateError>;
42
43pub(crate) fn get_error(status: reqwest::StatusCode, data: &str) -> ReplicateError {
44    match status {
45        StatusCode::PAYMENT_REQUIRED => {
46            let data: Option<ErrorData> = serde_json::from_str(data).ok();
47            if let Some(data) = data {
48                ReplicateError::PaymentNeeded(format!("{}: {}", data.title, data.detail))
49            } else {
50                ReplicateError::PaymentNeeded("error details not available".to_string())
51            }
52        }
53        StatusCode::UNAUTHORIZED => {
54            let data: Option<ErrorData> = serde_json::from_str(data).ok();
55            if let Some(data) = data {
56                ReplicateError::InvalidCredentials(format!("{}: {}", data.title, data.detail))
57            } else {
58                ReplicateError::InvalidCredentials("error details not available".to_string())
59            }
60        }
61        _ => {
62            println!("DATA: {:?}", data);
63            let data: Option<ErrorData> = serde_json::from_str(data).ok();
64            if let Some(data) = data {
65                ReplicateError::Misc(format!("{}: {}", data.title, data.detail))
66            } else {
67                ReplicateError::Misc("error details not available".to_string())
68            }
69        }
70    }
71}