use thiserror::Error as ThisError;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
pub enum RpcCode {
Ok = 200_000,
Internal = 200_050,
BadRequest = 200_400,
Unauthorized = 200_401,
Forbidden = 200_403,
NotFound = 200_404,
}
impl RpcCode {
pub const fn code(self) -> i32 {
self as i32
}
pub const fn message(self) -> &'static str {
match self {
Self::Ok => "OK",
Self::Internal => "Internal Error",
Self::BadRequest => "Bad Request",
Self::Unauthorized => "Unauthorized",
Self::Forbidden => "Forbidden",
Self::NotFound => "Not Found",
}
}
}
pub trait ErrorMapping: Send + Sync {
fn code(&self) -> i32;
fn is_public(&self) -> bool;
fn client_message(&self) -> String;
fn to_app_response(&self, endpoint: impl Into<String>) -> crate::AppResponse {
crate::AppResponse::error(self.code(), self.client_message()).with_endpoint(endpoint)
}
}
#[derive(Debug, ThisError)]
pub enum Error {
#[error("rpc error {code}: {message}")]
Biz {
code: i32,
message: String,
},
#[error("io error: {0}")]
Io(#[from] std::io::Error),
#[error("json error: {0}")]
Json(#[from] serde_json::Error),
#[error("protocol error: {0}")]
Protocol(String),
#[error("method not found: {0}")]
MethodNotFound(String),
#[error("validation error: {0}")]
Validation(String),
#[error("config error: {0}")]
Config(String),
}
impl Error {
pub fn biz(code: RpcCode, message: impl Into<String>) -> Self {
Self::Biz {
code: code.code(),
message: message.into(),
}
}
pub fn biz_code(code: i32, message: impl Into<String>) -> Self {
Self::Biz {
code,
message: message.into(),
}
}
pub fn code(&self) -> i32 {
ErrorMapping::code(self)
}
pub fn is_public(&self) -> bool {
ErrorMapping::is_public(self)
}
pub fn client_message(&self) -> String {
ErrorMapping::client_message(self)
}
pub fn to_app_response(&self, endpoint: impl Into<String>) -> crate::AppResponse {
ErrorMapping::to_app_response(self, endpoint)
}
}
impl ErrorMapping for Error {
fn code(&self) -> i32 {
match self {
Self::Biz { code, .. } => *code,
Self::MethodNotFound(_) => RpcCode::NotFound.code(),
Self::Validation(_) => RpcCode::BadRequest.code(),
_ => RpcCode::Internal.code(),
}
}
fn is_public(&self) -> bool {
matches!(
self,
Self::Biz { .. } | Self::Validation(_) | Self::MethodNotFound(_)
)
}
fn client_message(&self) -> String {
match self {
Self::Biz { message, .. } => message.clone(),
Self::Validation(m) => m.clone(),
Self::MethodNotFound(_) => RpcCode::NotFound.message().to_string(),
other => {
tracing::error!(error = %other, "internal rpc error (typed; not exposed to client)");
crate::sanitize::CLIENT_INTERNAL_MSG.to_string()
}
}
}
}