Skip to main content

functora_core/
error.rs

1use crate::i18n::I18N;
2use std::sync::Arc;
3
4#[derive(Debug, thiserror::Error)]
5#[error(transparent)]
6pub struct IoError(pub Arc<std::io::Error>);
7
8impl PartialEq for IoError {
9    fn eq(&self, other: &Self) -> bool {
10        Arc::ptr_eq(&self.0, &other.0)
11    }
12}
13impl Eq for IoError {}
14
15impl From<std::io::Error> for IoError {
16    fn from(e: std::io::Error) -> Self {
17        IoError(Arc::new(e))
18    }
19}
20
21#[derive(Debug, thiserror::Error)]
22#[error(transparent)]
23pub struct JsonError(pub Arc<serde_json::Error>);
24
25impl PartialEq for JsonError {
26    fn eq(&self, other: &Self) -> bool {
27        Arc::ptr_eq(&self.0, &other.0)
28    }
29}
30impl Eq for JsonError {}
31
32impl From<serde_json::Error> for JsonError {
33    fn from(e: serde_json::Error) -> Self {
34        JsonError(Arc::new(e))
35    }
36}
37
38#[cfg(feature = "zip")]
39#[derive(Debug, thiserror::Error)]
40#[error(transparent)]
41pub struct ZipErr(pub Arc<zip::result::ZipError>);
42
43#[cfg(feature = "zip")]
44impl PartialEq for ZipErr {
45    fn eq(&self, other: &Self) -> bool {
46        Arc::ptr_eq(&self.0, &other.0)
47    }
48}
49#[cfg(feature = "zip")]
50impl Eq for ZipErr {}
51
52#[cfg(feature = "zip")]
53impl From<zip::result::ZipError> for ZipErr {
54    fn from(e: zip::result::ZipError) -> Self {
55        ZipErr(Arc::new(e))
56    }
57}
58
59#[cfg(target_os = "android")]
60#[derive(Debug, thiserror::Error)]
61#[error(transparent)]
62pub struct JniError(pub Arc<jni::errors::Error>);
63
64#[cfg(target_os = "android")]
65impl PartialEq for JniError {
66    fn eq(&self, other: &Self) -> bool {
67        Arc::ptr_eq(&self.0, &other.0)
68    }
69}
70#[cfg(target_os = "android")]
71impl Eq for JniError {}
72
73#[cfg(target_os = "android")]
74impl From<jni::errors::Error> for JniError {
75    fn from(e: jni::errors::Error) -> Self {
76        JniError(Arc::new(e))
77    }
78}
79
80#[derive(Debug, PartialEq, Eq, thiserror::Error)]
81pub enum Error {
82    #[error("IO error: {0}")]
83    IO(IoError),
84    #[cfg(target_os = "android")]
85    #[error("JNI error: {0}")]
86    JNI(JniError),
87    #[error("JSON error: {0}")]
88    Json(JsonError),
89    #[error("Base64 decoding error: {0}")]
90    Base64(base64::DecodeError),
91    #[cfg(feature = "qr")]
92    #[error("QR code error: {0}")]
93    Qr(#[from] rxing::Exceptions),
94    #[error("Environment error: {0}")]
95    Env(#[from] std::env::VarError),
96    #[error("Channel error: {0}")]
97    Channel(#[from] std::sync::mpsc::RecvError),
98    #[error("JS error: {0}")]
99    JS(String),
100    #[error("Eval channel died before completion (dioxus internal GC/drop race)")]
101    EvalFinished,
102    #[cfg(feature = "crypto")]
103    #[error("Cipher initialization error: {0}")]
104    Cipher(cipher::InvalidLength),
105    #[cfg(feature = "crypto")]
106    #[error("Key derivation error: {0}")]
107    KeyDerive(#[from] argon2::Error),
108    #[cfg(feature = "crypto")]
109    #[error("Random number generation error: {0}")]
110    Getrandom(#[from] getrandom::Error),
111    #[cfg(feature = "crypto")]
112    #[error("Encryption failed: {0}")]
113    Encrypt(aead::Error),
114    #[cfg(feature = "crypto")]
115    #[error("Decryption failed: {0}")]
116    Decrypt(aead::Error),
117    #[error("Invalid encrypted payload format: {0}")]
118    InvalidFormat(String),
119    #[error("Numeric conversion failed ({context}): {source}")]
120    Convert {
121        context: &'static str,
122        source: std::num::TryFromIntError,
123    },
124    #[error("Camera not available: {0}")]
125    CameraNotAvailable(String),
126    #[error("Camera permission denied: {0}")]
127    CameraPermissionDenied(String),
128    #[error("Camera feed stalled: no frames received")]
129    CameraStalled,
130    #[error("Not a JSON object: {0}")]
131    NotJsonObject(serde_json::Value),
132    #[cfg(feature = "zip")]
133    #[error("Archive error: {0}")]
134    Archive(ZipErr),
135    #[error("Background task error: {0}")]
136    Worker(WorkerStopped),
137    #[error("File too large ({name}: {size} bytes, limit {limit} bytes)")]
138    FileTooLarge { name: String, size: u64, limit: u64 },
139    #[error("Operation cancelled")]
140    Cancelled,
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
144#[error("Background task stopped unexpectedly")]
145pub struct WorkerStopped;
146
147impl From<std::io::Error> for Error {
148    fn from(e: std::io::Error) -> Self {
149        Error::IO(IoError::from(e))
150    }
151}
152
153impl From<serde_json::Error> for Error {
154    fn from(e: serde_json::Error) -> Self {
155        Error::Json(JsonError::from(e))
156    }
157}
158
159impl From<base64::DecodeError> for Error {
160    fn from(e: base64::DecodeError) -> Self {
161        Error::Base64(e)
162    }
163}
164
165#[cfg(feature = "crypto")]
166impl From<cipher::InvalidLength> for Error {
167    fn from(e: cipher::InvalidLength) -> Self {
168        Error::Cipher(e)
169    }
170}
171
172#[cfg(target_os = "android")]
173impl From<jni::errors::Error> for Error {
174    fn from(e: jni::errors::Error) -> Self {
175        Error::JNI(JniError::from(e))
176    }
177}
178
179impl From<WorkerStopped> for Error {
180    fn from(e: WorkerStopped) -> Self {
181        Error::Worker(e)
182    }
183}
184
185#[cfg(feature = "zip")]
186impl From<zip::result::ZipError> for Error {
187    fn from(e: zip::result::ZipError) -> Self {
188        Error::Archive(ZipErr::from(e))
189    }
190}
191
192impl I18N for Error {
193    fn render_eng(&self) -> String {
194        match self {
195            Self::IO(e) => format!("IO error: {e}"),
196            Self::Json(e) => format!("JSON parsing error: {e}"),
197            Self::Base64(e) => format!("Base64 decoding error: {e}"),
198            #[cfg(feature = "qr")]
199            Self::Qr(e) => format!("QR code error: {e}"),
200            Self::Env(e) => format!("Environment variable error: {e}"),
201            Self::Channel(e) => format!("Channel receive error: {e}"),
202            Self::JS(e) => format!("JavaScript evaluation error: {e}"),
203            Self::EvalFinished => "The connection to the browser was lost; please try again".into(),
204            #[cfg(feature = "crypto")]
205            Self::Cipher(e) => format!("Cipher initialization error: {e}"),
206            #[cfg(feature = "crypto")]
207            Self::KeyDerive(e) => format!("Key derivation error: {e}"),
208            #[cfg(feature = "crypto")]
209            Self::Getrandom(e) => format!("Random number generation error: {e}"),
210            #[cfg(feature = "crypto")]
211            Self::Encrypt(e) => format!("Encryption failed: {e}"),
212            #[cfg(feature = "crypto")]
213            Self::Decrypt(e) => format!("Decryption failed: {e}"),
214            Self::InvalidFormat(e) => format!("Invalid encrypted payload format: {e}"),
215            Self::Convert { context, source } => {
216                format!("Numeric conversion failed ({context}): {source}")
217            }
218            Self::CameraNotAvailable(e) => format!("Camera is not available: {e}"),
219            Self::CameraPermissionDenied(e) => format!("Camera permission was denied: {e}"),
220            Self::CameraStalled => "The camera feed stopped responding; try again".into(),
221            Self::NotJsonObject(e) => format!("Expected JSON object, got: {e}"),
222            #[cfg(feature = "zip")]
223            Self::Archive(e) => format!("Archive error: {e}"),
224            Self::Worker(e) => format!("Background task error: {e}"),
225            Self::FileTooLarge { name, size, limit } => {
226                format!("File too large ({name}: {size} bytes, limit {limit} bytes)")
227            }
228            Self::Cancelled => "Operation cancelled".into(),
229            #[cfg(target_os = "android")]
230            Self::JNI(e) => format!("JNI error: {e}"),
231        }
232    }
233
234    fn render_spa(&self) -> String {
235        match self {
236            Self::IO(e) => format!("Error de E/S: {e}"),
237            Self::Json(e) => format!("Error de análisis JSON: {e}"),
238            Self::Base64(e) => format!("Error de decodificación Base64: {e}"),
239            #[cfg(feature = "qr")]
240            Self::Qr(e) => format!("Error de código QR: {e}"),
241            Self::Env(e) => format!("Error de variable de entorno: {e}"),
242            Self::Channel(e) => format!("Error de recepción en canal: {e}"),
243            Self::JS(e) => format!("Error de evaluación JavaScript: {e}"),
244            Self::EvalFinished => {
245                "Se perdió la conexión con el navegador; inténtalo de nuevo".into()
246            }
247            #[cfg(feature = "crypto")]
248            Self::Cipher(e) => format!("Error de inicialización de cifrado: {e}"),
249            #[cfg(feature = "crypto")]
250            Self::KeyDerive(e) => format!("Error de derivación de clave: {e}"),
251            #[cfg(feature = "crypto")]
252            Self::Getrandom(e) => format!("Error de generación de números aleatorios: {e}"),
253            #[cfg(feature = "crypto")]
254            Self::Encrypt(e) => format!("Falló el cifrado: {e}"),
255            #[cfg(feature = "crypto")]
256            Self::Decrypt(e) => format!("Falló el descifrado: {e}"),
257            Self::InvalidFormat(e) => format!("Formato de carga útil cifrada no válido: {e}"),
258            Self::Convert { context, source } => {
259                format!("Error de conversión numérica ({context}): {source}")
260            }
261            Self::CameraNotAvailable(e) => format!("La cámara no está disponible: {e}"),
262            Self::CameraPermissionDenied(e) => format!("Permiso de cámara denegado: {e}"),
263            Self::CameraStalled => "La cámara dejó de responder; inténtalo de nuevo".into(),
264            Self::NotJsonObject(e) => format!("Se esperaba un objeto JSON, se obtuvo: {e}"),
265            #[cfg(feature = "zip")]
266            Self::Archive(e) => format!("Error de archivo: {e}"),
267            Self::Worker(e) => {
268                format!("La tarea en segundo plano se detuvo inesperadamente (error: {e})")
269            }
270            Self::FileTooLarge { name, size, limit } => {
271                format!("Archivo demasiado grande ({name}: {size} bytes, límite {limit} bytes)")
272            }
273            Self::Cancelled => "Operación cancelada".into(),
274            #[cfg(target_os = "android")]
275            Self::JNI(e) => format!("Error JNI: {e}"),
276        }
277    }
278
279    fn render_rus(&self) -> String {
280        match self {
281            Self::IO(e) => format!("Ошибка ввода-вывода: {e}"),
282            Self::Json(e) => format!("Ошибка разбора JSON: {e}"),
283            Self::Base64(e) => format!("Ошибка декодирования Base64: {e}"),
284            #[cfg(feature = "qr")]
285            Self::Qr(e) => format!("Ошибка QR-кода: {e}"),
286            Self::Env(e) => format!("Ошибка переменной окружения: {e}"),
287            Self::Channel(e) => format!("Ошибка получения из канала: {e}"),
288            Self::JS(e) => format!("Ошибка выполнения JavaScript: {e}"),
289            Self::EvalFinished => "Соединение с браузером потеряно; попробуйте ещё раз".into(),
290            #[cfg(feature = "crypto")]
291            Self::Cipher(e) => format!("Ошибка инициализации шифра: {e}"),
292            #[cfg(feature = "crypto")]
293            Self::KeyDerive(e) => format!("Ошибка вывода ключа: {e}"),
294            #[cfg(feature = "crypto")]
295            Self::Getrandom(e) => format!("Ошибка генерации случайных чисел: {e}"),
296            #[cfg(feature = "crypto")]
297            Self::Encrypt(e) => format!("Ошибка шифрования: {e}"),
298            #[cfg(feature = "crypto")]
299            Self::Decrypt(e) => format!("Ошибка расшифровки: {e}"),
300            Self::InvalidFormat(e) => format!("Неверный формат зашифрованных данных: {e}"),
301            Self::Convert { context, source } => {
302                format!("Ошибка численного преобразования ({context}): {source}")
303            }
304            Self::CameraNotAvailable(e) => format!("Камера недоступна: {e}"),
305            Self::CameraPermissionDenied(e) => format!("Разрешение на камеру отклонено: {e}"),
306            Self::CameraStalled => "Поток с камеры остановился; попробуйте ещё раз".into(),
307            Self::NotJsonObject(e) => format!("Ожидался JSON-объект, получено: {e}"),
308            #[cfg(feature = "zip")]
309            Self::Archive(e) => format!("Ошибка архива: {e}"),
310            Self::Worker(e) => format!("Ошибка фоновой задачи: {e}"),
311            Self::FileTooLarge { name, size, limit } => {
312                format!("Файл слишком большой ({name}: {size} байт, лимит {limit} байт)")
313            }
314            Self::Cancelled => "Операция отменена".into(),
315            #[cfg(target_os = "android")]
316            Self::JNI(e) => format!("Ошибка JNI: {e}"),
317        }
318    }
319}