use alloc::borrow::{Cow, ToOwned};
use alloc::format;
use alloc::string::{String, ToString};
use core::fmt;
use crate::decode::{DecodeError, DecodeErrorKind};
use crate::version::Version;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCode {
FormatViolation,
GenericError,
InternalError,
MessageTypeNotSupported,
NotImplemented,
NotSupported,
OccurrenceConstraintViolation,
PropertyConstraintViolation,
ProtocolError,
RpcFrameworkError,
SecurityError,
TypeConstraintViolation,
Other(String),
}
impl ErrorCode {
#[must_use]
pub fn as_wire(&self, version: Version) -> &str {
let legacy = version == Version::V1_6;
match self {
ErrorCode::FormatViolation => {
if legacy {
"FormationViolation"
} else {
"FormatViolation"
}
}
ErrorCode::GenericError => "GenericError",
ErrorCode::InternalError => "InternalError",
ErrorCode::MessageTypeNotSupported => {
if legacy {
"GenericError"
} else {
"MessageTypeNotSupported"
}
}
ErrorCode::NotImplemented => "NotImplemented",
ErrorCode::NotSupported => "NotSupported",
ErrorCode::OccurrenceConstraintViolation => {
if legacy {
"OccurenceConstraintViolation"
} else {
"OccurrenceConstraintViolation"
}
}
ErrorCode::PropertyConstraintViolation => "PropertyConstraintViolation",
ErrorCode::ProtocolError => "ProtocolError",
ErrorCode::RpcFrameworkError => {
if legacy {
"GenericError"
} else {
"RpcFrameworkError"
}
}
ErrorCode::SecurityError => "SecurityError",
ErrorCode::TypeConstraintViolation => "TypeConstraintViolation",
ErrorCode::Other(code) => code.as_str(),
}
}
#[must_use]
pub fn parse(code: &str) -> Self {
match code {
"FormatViolation" | "FormationViolation" => ErrorCode::FormatViolation,
"GenericError" => ErrorCode::GenericError,
"InternalError" => ErrorCode::InternalError,
"MessageTypeNotSupported" => ErrorCode::MessageTypeNotSupported,
"NotImplemented" => ErrorCode::NotImplemented,
"NotSupported" => ErrorCode::NotSupported,
"OccurrenceConstraintViolation" | "OccurenceConstraintViolation" => {
ErrorCode::OccurrenceConstraintViolation
}
"PropertyConstraintViolation" => ErrorCode::PropertyConstraintViolation,
"ProtocolError" => ErrorCode::ProtocolError,
"RpcFrameworkError" => ErrorCode::RpcFrameworkError,
"SecurityError" => ErrorCode::SecurityError,
"TypeConstraintViolation" => ErrorCode::TypeConstraintViolation,
other => ErrorCode::Other(other.to_owned()),
}
}
#[must_use]
pub fn is_defined_in(&self, version: Version) -> bool {
match self {
ErrorCode::RpcFrameworkError | ErrorCode::MessageTypeNotSupported => {
version != Version::V1_6
}
ErrorCode::Other(_) => false,
_ => true,
}
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_wire(Version::V2_1))
}
}
pub const ERROR_DESCRIPTION_MAX_LEN: usize = 255;
fn cap_description(text: &str) -> String {
match text.char_indices().nth(ERROR_DESCRIPTION_MAX_LEN) {
Some((cut, _)) => text[..cut].to_owned(),
None => text.to_owned(),
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct CallError {
pub code: ErrorCode,
pub description: String,
pub details: serde_json::Value,
}
impl CallError {
#[must_use]
pub fn new(code: ErrorCode, description: impl Into<String>) -> Self {
Self {
code,
description: cap_description(&description.into()),
details: serde_json::Value::Object(serde_json::Map::new()),
}
}
#[must_use]
pub fn with_details(mut self, details: serde_json::Value) -> Self {
self.details = details;
self
}
#[must_use]
pub fn not_implemented(action: &str) -> Self {
Self::new(
ErrorCode::NotImplemented,
format!("unknown action {action:?}"),
)
}
#[must_use]
pub fn not_supported(action: &str) -> Self {
Self::new(
ErrorCode::NotSupported,
format!("action {action:?} is not supported"),
)
}
#[must_use]
pub fn internal(description: impl Into<String>) -> Self {
Self::new(ErrorCode::InternalError, description)
}
#[must_use]
pub fn security(description: impl Into<String>) -> Self {
Self::new(ErrorCode::SecurityError, description)
}
}
impl From<DecodeError> for CallError {
fn from(error: DecodeError) -> Self {
let code = match error.kind {
DecodeErrorKind::Format => ErrorCode::FormatViolation,
DecodeErrorKind::Occurrence => ErrorCode::OccurrenceConstraintViolation,
DecodeErrorKind::Type => ErrorCode::TypeConstraintViolation,
DecodeErrorKind::Property => ErrorCode::PropertyConstraintViolation,
DecodeErrorKind::UnknownField | DecodeErrorKind::Protocol => ErrorCode::ProtocolError,
DecodeErrorKind::UnsupportedAction => ErrorCode::NotSupported,
};
let mut details = serde_json::Map::new();
if !error.path.is_empty() {
details.insert(
"path".to_string(),
serde_json::Value::String(error.path.clone()),
);
}
details.insert(
"reason".to_string(),
serde_json::Value::String(error.reason.clone()),
);
Self {
code,
description: cap_description(&error.to_string()),
details: serde_json::Value::Object(details),
}
}
}
impl fmt::Display for CallError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.description.is_empty() {
write!(f, "{}", self.code)
} else {
write!(f, "{}: {}", self.code, self.description)
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for CallError {}
#[derive(Clone, Debug)]
pub struct CallErrorRef<'a> {
pub code: ErrorCode,
pub description: Cow<'a, str>,
pub details: Cow<'a, serde_json::value::RawValue>,
}
impl CallErrorRef<'_> {
#[must_use]
pub fn to_call_error(&self) -> CallError {
CallError {
code: self.code.clone(),
description: self.description.clone().into_owned(),
details: serde_json::from_str(self.details.get())
.unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new())),
}
}
#[must_use]
pub fn into_owned(self) -> CallErrorRef<'static> {
CallErrorRef {
code: self.code,
description: Cow::Owned(self.description.into_owned()),
details: Cow::Owned(self.details.into_owned()),
}
}
}
impl PartialEq for CallErrorRef<'_> {
fn eq(&self, other: &Self) -> bool {
self.code == other.code
&& self.description == other.description
&& self.details.get() == other.details.get()
}
}
impl From<CallError> for CallErrorRef<'static> {
fn from(error: CallError) -> Self {
CallErrorRef {
code: error.code,
description: Cow::Owned(cap_description(&error.description)),
details: Cow::Owned(
serde_json::value::to_raw_value(&error.details).unwrap_or_else(|_| {
serde_json::value::RawValue::from_string("{}".to_string()).expect("valid")
}),
),
}
}
}
impl From<&CallError> for CallErrorRef<'static> {
fn from(error: &CallError) -> Self {
CallErrorRef {
code: error.code.clone(),
description: Cow::Owned(cap_description(&error.description)),
details: Cow::Owned(
serde_json::value::to_raw_value(&error.details).unwrap_or_else(|_| {
serde_json::value::RawValue::from_string("{}".to_string()).expect("valid")
}),
),
}
}
}