kcode_intelligence_router/
error.rs1use std::fmt;
2
3use crate::UsageReceipt;
4
5#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub enum ErrorKind {
8 InvalidInput,
9 Unavailable,
10 Conflict,
11 Cancelled,
12 Provider,
13 Internal,
14}
15
16#[derive(Debug)]
18pub struct Error {
19 kind: ErrorKind,
20 code: &'static str,
21 message: String,
22 receipt: Option<Box<UsageReceipt>>,
23}
24
25impl Error {
26 pub(crate) fn new(kind: ErrorKind, code: &'static str, message: impl Into<String>) -> Self {
27 Self {
28 kind,
29 code,
30 message: message.into(),
31 receipt: None,
32 }
33 }
34
35 pub fn invalid(message: impl Into<String>) -> Self {
36 Self::new(ErrorKind::InvalidInput, "invalid_request", message)
37 }
38
39 pub(crate) fn unavailable(code: &'static str, message: impl Into<String>) -> Self {
40 Self::new(ErrorKind::Unavailable, code, message)
41 }
42
43 pub(crate) fn conflict(code: &'static str, message: impl Into<String>) -> Self {
44 Self::new(ErrorKind::Conflict, code, message)
45 }
46
47 pub(crate) fn cancelled() -> Self {
48 Self::new(
49 ErrorKind::Cancelled,
50 "operation_cancelled",
51 "The operation was stopped by the user.",
52 )
53 }
54
55 pub(crate) fn provider(code: &'static str, message: impl Into<String>) -> Self {
56 Self::new(ErrorKind::Provider, code, message)
57 }
58
59 pub(crate) fn internal(code: &'static str, message: impl Into<String>) -> Self {
60 Self::new(ErrorKind::Internal, code, message)
61 }
62
63 pub fn kind(&self) -> ErrorKind {
64 self.kind
65 }
66
67 pub fn code(&self) -> &'static str {
68 self.code
69 }
70
71 pub fn message(&self) -> &str {
72 &self.message
73 }
74
75 pub fn receipt(&self) -> Option<&UsageReceipt> {
77 self.receipt.as_deref()
78 }
79
80 pub(crate) fn with_receipt(mut self, receipt: UsageReceipt) -> Self {
81 self.receipt = Some(Box::new(receipt));
82 self
83 }
84
85 pub fn retryable(&self) -> bool {
87 matches!(self.kind, ErrorKind::Provider | ErrorKind::Conflict)
88 || (self.kind == ErrorKind::Unavailable && self.code != "provider_not_configured")
89 }
90}
91
92impl fmt::Display for Error {
93 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
94 formatter.write_str(&self.message)
95 }
96}
97
98impl std::error::Error for Error {}
99
100pub type Result<T> = std::result::Result<T, Error>;
101
102#[cfg(test)]
103mod tests {
104 use super::*;
105
106 #[test]
107 fn retryability_distinguishes_configuration_from_transient_provider_failure() {
108 assert!(!Error::unavailable("provider_not_configured", "missing key").retryable());
109 assert!(Error::unavailable("provider_rate_limited", "try later").retryable());
110 assert!(Error::provider("provider_timeout", "try later").retryable());
111 assert!(!Error::invalid("bad request").retryable());
112 }
113}