use std::collections::HashMap;
use serde::Deserialize;
use thiserror::Error;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Error)]
pub enum Error {
#[error(transparent)]
Api(#[from] ApiError),
#[error("vectoramp: http transport error: {0}")]
Http(#[from] reqwest::Error),
#[error("vectoramp: json error: {0}")]
Json(#[from] serde_json::Error),
#[error("vectoramp: invalid url: {0}")]
Url(#[from] url::ParseError),
#[error("vectoramp: io error: {0}")]
Io(#[from] std::io::Error),
#[error("vectoramp: invalid input: {0}")]
InvalidInput(String),
#[error("vectoramp: stream error: {0}")]
Stream(String),
#[error("vectoramp: {0}")]
Other(String),
}
impl Error {
pub fn invalid_input<S: Into<String>>(msg: S) -> Self {
Error::InvalidInput(msg.into())
}
}
#[derive(Debug, Error)]
#[error("vectoramp: api error {status}: {message}")]
pub struct ApiError {
pub status: u16,
pub message: String,
pub body: Vec<u8>,
pub headers: HashMap<String, String>,
}
impl ApiError {
pub(crate) fn from_parts(status: u16, headers: HashMap<String, String>, body: Vec<u8>) -> Self {
let message = extract_message(&body).unwrap_or_else(|| {
String::from_utf8_lossy(&body)
.trim()
.chars()
.take(512)
.collect()
});
ApiError {
status,
message,
body,
headers,
}
}
}
#[derive(Debug, Deserialize)]
struct ErrorBody {
error: Option<String>,
message: Option<String>,
detail: Option<String>,
}
fn extract_message(body: &[u8]) -> Option<String> {
let parsed: ErrorBody = serde_json::from_slice(body).ok()?;
parsed.error.or(parsed.message).or(parsed.detail)
}