common_helpers/
rpc.rs

1use core::result::Result as CoreResult;
2use jsonrpsee::{
3	core::RpcResult,
4	types::error::{ErrorCode, ErrorObject},
5};
6use sp_api::ApiError;
7
8/// Converts CoreResult to Result for RPC calls
9pub fn map_rpc_result<T>(response: CoreResult<T, ApiError>) -> RpcResult<T> {
10	match response {
11		Ok(res) => Ok(res),
12		Err(e) => Err(ErrorObject::owned(
13			ErrorCode::ServerError(300).code(), // No real reason for this value
14			"Api Error",
15			Some(format!("{e:?}")),
16		)),
17	}
18}
19
20#[cfg(test)]
21mod tests {
22	use super::*;
23
24	// It is enough to test that we are getting into the correct match statement.
25
26	#[test]
27	fn maps_ok_to_ok() {
28		let result = map_rpc_result(Ok(0));
29		assert!(result.is_ok());
30		assert_eq!(0, result.unwrap());
31	}
32
33	#[test]
34	fn maps_err_to_api_err() {
35		let result = map_rpc_result::<u64>(Err(ApiError::StateBackendIsNotTrie));
36		assert!(result.is_err());
37		let str = format!("{:?}", result.err().unwrap());
38		assert!(str.contains("Api Error"), "Did not find in: {:?}", str);
39	}
40}