From 6c7a8967257ce92ed80bc21ddadf838933e64a52 Mon Sep 17 00:00:00 2001 From: Eval EXEC Date: Tue, 26 Nov 2024 11:38:08 +0800 Subject: [PATCH] Remove rpc backtrace, resolve #4698 --- rpc/src/error.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/rpc/src/error.rs b/rpc/src/error.rs index 753f747dbe..b86fea85b3 100644 --- a/rpc/src/error.rs +++ b/rpc/src/error.rs @@ -153,15 +153,43 @@ impl RPCError { } } + /// Removes the backtrace portion from an error string. + /// + /// This function processes the input string `err_str` line by line and collects all lines + /// until it encounters a line starting with "Stack backtrace:". It then joins the collected + /// lines into a single string, effectively removing the backtrace section. + /// + /// # Arguments + /// * `err_str` - A string slice containing the error message, potentially including a backtrace. + /// + /// # Returns + /// * A `String` containing the error message without the backtrace. + /// + /// # Example + /// ``` + /// let error_message = "Error: Something went wrong\nStack backtrace:\n1: some_function\n2: another_function"; + /// let cleaned_message = remove_backtrace(error_message); + /// assert_eq!(cleaned_message, "Error: Something went wrong"); + /// ``` + fn remove_backtrace(err_str: &str) -> String { + let lines: Vec<_> = err_str + .lines() + .take_while(|line| !line.starts_with("Stack backtrace:")) + .collect(); + lines.join("\n") + } + /// Creates an RPC error from std error with the custom error code. /// /// The parameter `err` is usually an std error. The Display form is used as the error message, /// and the Debug form is used as the data. pub fn custom_with_error(error_code: RPCError, err: T) -> Error { + let err_str_with_backtrace = format!("{err:?}"); + let err_str = remove_backtrace(err_str_with_backtrace); Error { code: ErrorCode::ServerError(error_code as i64), message: format!("{error_code:?}: {err}"), - data: Some(Value::String(format!("{err:?}"))), + data: Some(Value::String(err_str)), } }