CH-J Tools透過 SSH 管理伺服器
選單
已發布的原始碼

CH-J Tools

瀏覽特定應用程式版本的目錄與檔案。

下載原始碼 ZIP
CH-J / Server Manager 1704 個檔案
0.1.2-beta 新增時間: · 建置時間:
error.rs 新增時間: 未記錄日期 2.5 KB · 85 行
程式碼 下載檔案
1//! Structured error shared by all Core services.
2//!
3//! The JSON shape (`code`, `message` and optional detail fields) matches the
4//! Electron 0.1.0 contract (`SessionError.toJSON`, diagnostics/biometric
5//! envelopes), so the unchanged renderer code keeps working.
7use serde::Serialize;
8use serde_json::{Map, Value};
9use std::fmt;
11#[derive(Debug, Clone, Serialize)]
12pub struct CoreError {
13 pub code: String,
14 pub message: String,
15 #[serde(flatten)]
16 pub details: Map<String, Value>,
19pub type CoreResult<T> = Result<T, CoreError>;
21impl CoreError {
22 pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
23 Self { code: code.into(), message: message.into(), details: Map::new() }
24 }
26 /// Error without a public code (Electron handlers that only threw `new Error(message)`).
27 pub fn plain(message: impl Into<String>) -> Self {
28 Self::new("", message)
29 }
31 pub fn with(mut self, key: &str, value: impl Into<Value>) -> Self {
32 self.details.insert(key.to_string(), value.into());
33 self
34 }
36 pub fn has_code(&self) -> bool {
37 !self.code.is_empty()
38 }
40 /// Message with a `CODE: ` prefix, as the plugin runtime of 0.1.0 exposed it.
41 pub fn prefixed_message(&self) -> String {
42 if self.code.is_empty() || self.message.starts_with(&format!("{}:", self.code)) {
43 self.message.clone()
44 } else {
45 format!("{}: {}", self.code, self.message)
46 }
47 }
50impl fmt::Display for CoreError {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 if self.code.is_empty() {
53 write!(f, "{}", self.message)
54 } else {
55 write!(f, "{}: {}", self.code, self.message)
56 }
57 }
60impl std::error::Error for CoreError {}
62impl From<std::io::Error> for CoreError {
63 fn from(error: std::io::Error) -> Self {
64 let code = match error.kind() {
65 std::io::ErrorKind::NotFound => "ENOENT",
66 std::io::ErrorKind::PermissionDenied => "EACCES",
67 std::io::ErrorKind::AlreadyExists => "EEXIST",
68 _ => "EIO",
69 };
70 CoreError::new(code, error.to_string())
71 }
74impl From<serde_json::Error> for CoreError {
75 fn from(error: serde_json::Error) -> Self {
76 CoreError::new("INVALID_JSON", error.to_string())
77 }
80#[macro_export]
81macro_rules! bail {
82 ($code:expr, $($arg:tt)*) => {
83 return Err($crate::core::error::CoreError::new($code, format!($($arg)*)))
84 };
SHA-2562dddbf80e310eb29c76530afab399239b5dd3a17787ddc8f851ecea1bd44dc5f

CH-J Proprietary Software License 1.14 · 原始碼依 CH-J Proprietary Software License 1.14 提供。公開原始碼不會改變授權條款,也不會授予額外的權利。

壓縮檔 SHA-256ac8fe790f4ba60fc098f8c985fc2656cfcc6cdc21fb34b30e308a2b54e62258f
檔案