error.rs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. use std::env::VarError;
  2. use std::fmt::{Display, Formatter};
  3. #[derive(Debug)]
  4. pub enum ApiError {
  5. MissingApiKey,
  6. InvalidApiKeyEnv(VarError),
  7. Http(reqwest::Error),
  8. Io(std::io::Error),
  9. Json(serde_json::Error),
  10. UnexpectedStatus {
  11. status: reqwest::StatusCode,
  12. body: String,
  13. },
  14. InvalidSseFrame(&'static str),
  15. }
  16. impl Display for ApiError {
  17. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  18. match self {
  19. Self::MissingApiKey => {
  20. write!(
  21. f,
  22. "ANTHROPIC_API_KEY is not set; export it before calling the Anthropic API"
  23. )
  24. }
  25. Self::InvalidApiKeyEnv(error) => {
  26. write!(f, "failed to read ANTHROPIC_API_KEY: {error}")
  27. }
  28. Self::Http(error) => write!(f, "http error: {error}"),
  29. Self::Io(error) => write!(f, "io error: {error}"),
  30. Self::Json(error) => write!(f, "json error: {error}"),
  31. Self::UnexpectedStatus { status, body } => {
  32. write!(f, "anthropic api returned {status}: {body}")
  33. }
  34. Self::InvalidSseFrame(message) => write!(f, "invalid sse frame: {message}"),
  35. }
  36. }
  37. }
  38. impl std::error::Error for ApiError {}
  39. impl From<reqwest::Error> for ApiError {
  40. fn from(value: reqwest::Error) -> Self {
  41. Self::Http(value)
  42. }
  43. }
  44. impl From<std::io::Error> for ApiError {
  45. fn from(value: std::io::Error) -> Self {
  46. Self::Io(value)
  47. }
  48. }
  49. impl From<serde_json::Error> for ApiError {
  50. fn from(value: serde_json::Error) -> Self {
  51. Self::Json(value)
  52. }
  53. }
  54. impl From<VarError> for ApiError {
  55. fn from(value: VarError) -> Self {
  56. Self::InvalidApiKeyEnv(value)
  57. }
  58. }