cfx_rpc_utils/error/
jsonrpsee_error_helpers.rs

1use jsonrpc_core::Error as JsonRpcError;
2use jsonrpsee::types::{
3    self as jsonrpsee_types,
4    error::{
5        ErrorObjectOwned, INTERNAL_ERROR_CODE, INVALID_PARAMS_CODE,
6        INVALID_REQUEST_CODE,
7    },
8};
9
10pub fn jsonrpc_error_to_error_object_owned(
11    e: JsonRpcError,
12) -> ErrorObjectOwned {
13    ErrorObjectOwned::owned(e.code.code() as i32, e.message, e.data)
14}
15
16pub fn invalid_params_msg(param: &str) -> ErrorObjectOwned {
17    invalid_params_rpc_err(format!("Invalid parameters: {}", param))
18}
19
20pub fn invalid_request_msg(param: &str) -> ErrorObjectOwned {
21    let data: Option<bool> = None;
22    ErrorObjectOwned::owned(INVALID_REQUEST_CODE, param, data)
23}
24
25pub fn invalid_params_rpc_err(msg: impl Into<String>) -> ErrorObjectOwned {
26    let data: Option<bool> = None;
27    ErrorObjectOwned::owned(INVALID_PARAMS_CODE, msg, data)
28}
29
30pub fn internal_error(msg: impl Into<String>) -> ErrorObjectOwned {
31    let data: Option<bool> = None;
32    ErrorObjectOwned::owned(INTERNAL_ERROR_CODE, msg, data)
33}
34
35/// Constructs an internal JSON-RPC error.
36pub fn internal_rpc_err(msg: impl Into<String>) -> ErrorObjectOwned {
37    rpc_err(jsonrpsee_types::error::INTERNAL_ERROR_CODE, msg, None)
38}
39
40/// Constructs an internal JSON-RPC error with data
41pub fn internal_rpc_err_with_data(
42    msg: impl Into<String>, data: &[u8],
43) -> ErrorObjectOwned {
44    rpc_err(jsonrpsee_types::error::INTERNAL_ERROR_CODE, msg, Some(data))
45}
46
47/// Constructs an internal JSON-RPC error with code and message
48pub fn rpc_error_with_code(
49    code: i32, msg: impl Into<String>,
50) -> ErrorObjectOwned {
51    rpc_err(code, msg, None)
52}
53
54/// Constructs a JSON-RPC error, consisting of `code`, `message` and optional
55/// `data`.
56pub fn rpc_err(
57    code: i32, msg: impl Into<String>, data: Option<&[u8]>,
58) -> ErrorObjectOwned {
59    ErrorObjectOwned::owned(
60        code,
61        msg.into(),
62        data.map(|data| {
63            jsonrpsee_core::to_json_raw_value(
64                &alloy_primitives::hex::encode_prefixed(data),
65            )
66            .expect("serializing String can't fail")
67        }),
68    )
69}