From 9dae54a3ed2f5af35d01383974848eb49207733d Mon Sep 17 00:00:00 2001 From: Ikechukwu Ahiara Marvellous Date: Thu, 16 Feb 2023 17:51:34 +0100 Subject: [PATCH] feat: add Error extension trait for `Result>` (#1381) Co-authored-by: Georgios Konstantopoulos Co-authored-by: Matthias Seitz --- crates/rpc/rpc/src/result.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/crates/rpc/rpc/src/result.rs b/crates/rpc/rpc/src/result.rs index cb01f4ae6f..52d7050807 100644 --- a/crates/rpc/rpc/src/result.rs +++ b/crates/rpc/rpc/src/result.rs @@ -1,8 +1,12 @@ //! Additional helpers for converting errors. use jsonrpsee::core::{Error as RpcError, RpcResult}; +use reth_interfaces::Result as RethResult; +use reth_primitives::Block; use std::fmt::Display; +use crate::eth::error::EthApiError; + /// Helper trait to easily convert various `Result` types into [`RpcResult`] pub(crate) trait ToRpcResult { /// Converts the error of the [Result] to an [RpcResult] via the `Err` [Display] impl. @@ -104,6 +108,30 @@ macro_rules! impl_to_rpc_result { impl_to_rpc_result!(reth_interfaces::Error); impl_to_rpc_result!(reth_network_api::NetworkError); +/// An extension to used to apply error conversions to various result types +pub(crate) trait ToRpcResultExt { + /// The `Ok` variant of the [RpcResult] + type Ok; + + /// Maps the `Ok` variant of this type into [Self::Ok] and maps the `Err` variant into rpc + /// error. + fn map_ok_or_rpc_err(self) -> RpcResult<::Ok>; +} + +impl ToRpcResultExt for RethResult> { + type Ok = Block; + + fn map_ok_or_rpc_err(self) -> RpcResult<::Ok> { + match self { + Ok(block) => match block { + Some(value) => Ok(value), + None => Err(EthApiError::UnknownBlockNumber.into()), + }, + Err(err) => Err(internal_rpc_err(err.to_string())), + } + } +} + /// Constructs an internal JSON-RPC error. pub(crate) fn internal_rpc_err(msg: impl Into) -> jsonrpsee::core::Error { rpc_err(jsonrpsee::types::error::INTERNAL_ERROR_CODE, msg, None) @@ -133,6 +161,7 @@ pub(crate) fn rpc_err(code: i32, msg: impl Into, data: Option<&[u8]>) -> #[cfg(test)] mod tests { + use super::*; fn assert_rpc_result>() {} @@ -141,6 +170,10 @@ mod tests { Ok(o) } + fn to_optional_reth_err(o: Ok) -> reth_interfaces::Result> { + Ok(Some(o)) + } + #[test] fn can_convert_rpc() { assert_rpc_result::<(), reth_interfaces::Error, reth_interfaces::Result<()>>();