Improve RPC handler error handling

This commit is contained in:
Samuel Lorch 2023-10-29 22:42:58 +01:00
parent 30b314d16a
commit 4edc1a494f

View file

@ -1,4 +1,5 @@
use crate::AppState; use crate::AppState;
use anyhow::Context;
use axum::routing::post; use axum::routing::post;
use axum::{Json, Router}; use axum::{Json, Router};
use jsonrpsee::core::traits::ToRpcParams; use jsonrpsee::core::traits::ToRpcParams;
@ -10,6 +11,8 @@ use axum::{extract::Extension, extract::State, response::IntoResponse};
use tracing::info; use tracing::info;
const JSON_RPC_VERSION: &str = "2.0";
// TODO fix this "workaround" // TODO fix this "workaround"
struct ParamConverter { struct ParamConverter {
params: Option<Box<RawValue>>, params: Option<Box<RawValue>>,
@ -66,19 +69,48 @@ async fn api_handler(
session: Extension<super::auth::Session>, session: Extension<super::auth::Session>,
body: String, body: String,
) -> impl IntoResponse { ) -> impl IntoResponse {
info!("api hit! user: {:?}", session.username); let req: RpcRequest = match serde_json::from_str(&body) {
Ok(req) => req,
// TODO handle Parse Error Err(err) => {
let req: RpcRequest = serde_json::from_str(&body).unwrap(); return Json(RpcResponse {
id: 0,
// TODO check version jsonrpc: JSON_RPC_VERSION.to_string(),
result: None,
let params = ParamConverter { params: req.params }; error: Some(RpcErrorObject {
// TODO Send back correct code
code: 0,
message: err.to_string(),
data: None,
}),
});
}
};
if req.jsonrpc != JSON_RPC_VERSION {
return Json(RpcResponse {
id: req.id,
jsonrpc: JSON_RPC_VERSION.to_string(),
result: None,
error: Some(RpcErrorObject {
// TODO Send back correct code
code: 0,
message: "Invalid Jsonrpc Version".to_string(),
data: None,
}),
});
}
// TODO check Permissions for method here? // TODO check Permissions for method here?
let res: Result<Option<Box<RawValue>>, Error> = info!(
state.rpc_module.call(&req.method, params).await; "api hit! user: {:?} method: {:?}",
session.username, req.method
);
// TODO find a async save way to catch panics?
let res: Result<Option<Box<RawValue>>, Error> = state
.rpc_module
.call(&req.method, ParamConverter { params: req.params })
.await;
match res { match res {
Ok(res) => Json(RpcResponse { Ok(res) => Json(RpcResponse {