error.rs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use log::error;
  19. use darkfi::{
  20. rpc::jsonrpc::{ErrorCode::ServerError, JsonError, JsonResult},
  21. Error,
  22. };
  23. /// Custom RPC errors available for blockchain explorer.
  24. /// Please sort them sensefully.
  25. pub enum RpcError {
  26. // Misc errors
  27. PingFailed = -32300,
  28. }
  29. fn to_tuple(e: RpcError) -> (i32, String) {
  30. let msg = match e {
  31. // Misc errors
  32. RpcError::PingFailed => "Darkfid daemon ping error",
  33. };
  34. (e as i32, msg.to_string())
  35. }
  36. pub fn server_error(e: RpcError, id: u16, msg: Option<&str>) -> JsonResult {
  37. let (code, default_msg) = to_tuple(e);
  38. if let Some(message) = msg {
  39. return JsonError::new(ServerError(code), Some(message.to_string()), id).into()
  40. }
  41. JsonError::new(ServerError(code), Some(default_msg), id).into()
  42. }
  43. /// Handles a database error by formatting the output, logging it with target-specific context,
  44. /// and returning a [`DatabaseError`].
  45. pub fn handle_database_error(target: &str, message: &str, error: impl std::fmt::Debug) -> Error {
  46. let error_message = format!("{}: {:?}", message, error);
  47. let formatted_target = format!("blockchain-explorer:: {target}");
  48. error!(target: &formatted_target, "{}", error_message);
  49. Error::DatabaseError(error_message)
  50. }