use std::fmt;
use serde_json::{Map, Value};
use crate::codes::{Category, Code};
#[derive(Clone, Debug)]
pub struct Fault {
code: Code,
category: Category,
retryable: bool,
message: String,
details: Value,
hint: String,
}
impl Fault {
pub fn new(code: Code, message: impl Into<String>) -> Fault {
Fault {
category: code.category(),
retryable: code.retryable(),
code,
message: message.into(),
details: Value::Object(Map::new()),
hint: String::new(),
}
}
pub fn code(&self) -> &Code {
&self.code
}
pub fn category(&self) -> Category {
self.category
}
pub fn retryable(&self) -> bool {
self.retryable
}
pub fn message(&self) -> &str {
&self.message
}
pub fn details(&self) -> &Value {
&self.details
}
pub fn hint(&self) -> &str {
&self.hint
}
}
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum Error {
Input(Fault),
Json(Fault),
Host(Fault),
Query(Fault),
Mutation(Fault),
Domain(Fault),
Panic(Fault),
Other(Fault),
}
impl Error {
pub fn invalid(message: impl Into<String>) -> Error {
Error::Input(Fault::new(Code::InvalidToolInput, message))
}
pub fn denied(message: impl Into<String>) -> Error {
Error::Domain(Fault::new(Code::QueryForbidden, message))
}
pub fn timed_out(message: impl Into<String>) -> Error {
Error::Domain(Fault::new(Code::QueryTimeout, message))
}
pub fn unavailable(message: impl Into<String>) -> Error {
Error::Domain(Fault::new(Code::DatabaseUnavailable, message))
}
pub fn failed(message: impl Into<String>) -> Error {
Error::Domain(Fault::new(Code::unspecified(), message))
}
pub fn domain(code: impl Into<String>, message: impl Into<String>) -> Error {
Error::Domain(Fault::new(Code::Custom(code.into()), message))
}
pub fn other(cause: impl fmt::Display) -> Error {
Error::Other(Fault::new(Code::unspecified(), cause.to_string()))
}
pub fn hint(mut self, hint: impl Into<String>) -> Error {
self.fault_mut().hint = hint.into();
self
}
pub fn details(mut self, details: Value) -> Error {
self.fault_mut().details = match details {
object @ Value::Object(_) => object,
other => {
let mut wrapper = Map::new();
wrapper.insert("detail".to_string(), other);
Value::Object(wrapper)
}
};
self
}
pub fn code_of(mut self, code: Code) -> Error {
let fault = self.fault_mut();
fault.category = code.category();
fault.retryable = code.retryable();
fault.code = code;
self
}
pub fn category_of(mut self, category: Category) -> Error {
self.fault_mut().category = category;
self
}
pub fn retryable(mut self, retryable: bool) -> Error {
let fault = self.fault_mut();
fault.retryable = fault.retryable && retryable;
self
}
pub fn fault(&self) -> &Fault {
match self {
Error::Input(fault)
| Error::Json(fault)
| Error::Host(fault)
| Error::Query(fault)
| Error::Mutation(fault)
| Error::Domain(fault)
| Error::Panic(fault)
| Error::Other(fault) => fault,
}
}
pub fn code(&self) -> &Code {
self.fault().code()
}
pub fn category(&self) -> Category {
self.fault().category()
}
pub fn message(&self) -> &str {
self.fault().message()
}
pub fn is_retryable(&self) -> bool {
self.fault().retryable()
}
pub fn body(&self) -> Value {
crate::envelope::error_body(self)
}
fn fault_mut(&mut self) -> &mut Fault {
match self {
Error::Input(fault)
| Error::Json(fault)
| Error::Host(fault)
| Error::Query(fault)
| Error::Mutation(fault)
| Error::Domain(fault)
| Error::Panic(fault)
| Error::Other(fault) => fault,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.message())
}
}
impl<E> From<E> for Error
where
E: std::error::Error + 'static,
{
fn from(cause: E) -> Error {
Error::Other(Fault::new(Code::unspecified(), cause.to_string()))
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn a_constructor_takes_its_codes_category_and_verdict() {
let timeout = Error::timed_out("The read timed out.");
assert_eq!(timeout.code().as_str(), "QUERY_TIMEOUT");
assert_eq!(timeout.category(), Category::Timeout);
assert!(timeout.is_retryable());
}
#[test]
fn retryability_narrows_and_never_widens() {
let narrowed = Error::timed_out("x").retryable(false);
assert!(!narrowed.is_retryable());
let widened = Error::invalid("x").retryable(true);
assert!(!widened.is_retryable());
}
#[test]
fn details_that_are_not_an_object_are_wrapped_in_one() {
let error = Error::invalid("x").details(json!(["a", "b"]));
assert_eq!(
error.fault().details(),
&json!({ "detail": ["a", "b"] }),
"details is always a JSON object on the wire"
);
}
#[test]
fn a_foreign_error_converts_through_the_question_mark() {
fn convert() -> Result<(), Error> {
let _: i64 = "nope".parse()?;
Ok(())
}
let error = convert().unwrap_err();
assert!(matches!(error, Error::Other(_)));
assert_eq!(error.code().as_str(), crate::codes::UNSPECIFIED);
}
#[test]
fn display_is_the_message_alone() {
let error = Error::invalid("'ids' is required.").hint("Pass one id.");
assert_eq!(error.to_string(), "'ids' is required.");
}
}