Просмотр исходного кода

explorer/error: added `handle_database_error` function for reusable error handling

This change introduces a reusable function to format error messages, add target-specific logging context, and encapsulate errors into a `DatabaseError`.
kalm 1 год назад
Родитель
Сommit
26f69b3e16
1 измененных файлов с 16 добавлено и 1 удалено
  1. 16 1
      script/research/blockchain-explorer/src/error.rs

+ 16 - 1
script/research/blockchain-explorer/src/error.rs

@@ -16,7 +16,12 @@
  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  */
 
-use darkfi::rpc::jsonrpc::{ErrorCode::ServerError, JsonError, JsonResult};
+use log::error;
+
+use darkfi::{
+    rpc::jsonrpc::{ErrorCode::ServerError, JsonError, JsonResult},
+    Error,
+};
 
 /// Custom RPC errors available for blockchain explorer.
 /// Please sort them sensefully.
@@ -43,3 +48,13 @@ pub fn server_error(e: RpcError, id: u16, msg: Option<&str>) -> JsonResult {
 
     JsonError::new(ServerError(code), Some(default_msg), id).into()
 }
+
+/// Handles a database error by formatting the output, logging it with target-specific context,
+/// and returning a [`DatabaseError`].
+#[allow(dead_code)] // TODO: Remove once code that uses this function is rebased into master
+pub fn handle_database_error(target: &str, message: &str, error: impl std::fmt::Debug) -> Error {
+    let error_message = format!("{}: {:?}", message, error);
+    let formatted_target = format!("blockchain-explorer:: {target}");
+    error!(target: &formatted_target, "{}", error_message);
+    Error::DatabaseError(error_message)
+}