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("No QR found in image")]
101    QrNotFound,
102    #[error("Eval channel died before completion (dioxus internal GC/drop race)")]
103    EvalFinished,
104    #[cfg(feature = "crypto")]
105    #[error("Cipher initialization error: {0}")]
106    Cipher(cipher::InvalidLength),
107    #[cfg(feature = "crypto")]
108    #[error("Key derivation error: {0}")]
109    KeyDerive(#[from] argon2::Error),
110    #[cfg(feature = "crypto")]
111    #[error("Random number generation error: {0}")]
112    Getrandom(#[from] getrandom::Error),
113    #[cfg(feature = "crypto")]
114    #[error("Encryption failed: {0}")]
115    Encrypt(aead::Error),
116    #[cfg(feature = "crypto")]
117    #[error("Decryption failed: {0}")]
118    Decrypt(aead::Error),
119    #[error("Invalid encrypted payload format: {0}")]
120    InvalidFormat(String),
121    #[error("Numeric conversion failed ({context}): {source}")]
122    Convert {
123        context: &'static str,
124        source: std::num::TryFromIntError,
125    },
126    #[error("Camera not available: {0}")]
127    CameraNotAvailable(String),
128    #[error("Camera permission denied: {0}")]
129    CameraPermissionDenied(String),
130    #[error("Camera feed stalled: no frames received")]
131    CameraStalled,
132    #[error("Not a JSON object: {0}")]
133    NotJsonObject(serde_json::Value),
134    #[cfg(feature = "zip")]
135    #[error("Archive error: {0}")]
136    Archive(ZipErr),
137    #[error("Background task error: {0}")]
138    Worker(WorkerStopped),
139    #[error("File too large ({name}: {size} bytes, limit {limit} bytes)")]
140    FileTooLarge { name: String, size: u64, limit: u64 },
141    #[error("Operation cancelled")]
142    Cancelled,
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
146#[error("Background task stopped unexpectedly")]
147pub struct WorkerStopped;
148
149impl From<std::io::Error> for Error {
150    fn from(e: std::io::Error) -> Self {
151        Error::IO(IoError::from(e))
152    }
153}
154
155impl From<serde_json::Error> for Error {
156    fn from(e: serde_json::Error) -> Self {
157        Error::Json(JsonError::from(e))
158    }
159}
160
161impl From<base64::DecodeError> for Error {
162    fn from(e: base64::DecodeError) -> Self {
163        Error::Base64(e)
164    }
165}
166
167#[cfg(feature = "crypto")]
168impl From<cipher::InvalidLength> for Error {
169    fn from(e: cipher::InvalidLength) -> Self {
170        Error::Cipher(e)
171    }
172}
173
174#[cfg(target_os = "android")]
175impl From<jni::errors::Error> for Error {
176    fn from(e: jni::errors::Error) -> Self {
177        Error::JNI(JniError::from(e))
178    }
179}
180
181impl From<WorkerStopped> for Error {
182    fn from(e: WorkerStopped) -> Self {
183        Error::Worker(e)
184    }
185}
186
187#[cfg(feature = "zip")]
188impl From<zip::result::ZipError> for Error {
189    fn from(e: zip::result::ZipError) -> Self {
190        Error::Archive(ZipErr::from(e))
191    }
192}
193
194impl I18N for Error {
195    fn render_eng(&self) -> String {
196        match self {
197            Self::IO(e) => format!("IO error: {e}"),
198            Self::Json(e) => format!("JSON parsing error: {e}"),
199            Self::Base64(e) => format!("Base64 decoding error: {e}"),
200            #[cfg(feature = "qr")]
201            Self::Qr(e) => format!("QR code error: {e}"),
202            Self::Env(e) => format!("Environment variable error: {e}"),
203            Self::Channel(e) => format!("Channel receive error: {e}"),
204            Self::JS(e) => format!("JavaScript evaluation error: {e}"),
205            Self::QrNotFound => "No QR found in image".into(),
206            Self::EvalFinished => "The connection to the browser was lost; please try again".into(),
207            #[cfg(feature = "crypto")]
208            Self::Cipher(e) => format!("Cipher initialization error: {e}"),
209            #[cfg(feature = "crypto")]
210            Self::KeyDerive(e) => format!("Key derivation error: {e}"),
211            #[cfg(feature = "crypto")]
212            Self::Getrandom(e) => format!("Random number generation error: {e}"),
213            #[cfg(feature = "crypto")]
214            Self::Encrypt(e) => format!("Encryption failed: {e}"),
215            #[cfg(feature = "crypto")]
216            Self::Decrypt(e) => format!("Decryption failed: {e}"),
217            Self::InvalidFormat(e) => format!("Invalid encrypted payload format: {e}"),
218            Self::Convert { context, source } => {
219                format!("Numeric conversion failed ({context}): {source}")
220            }
221            Self::CameraNotAvailable(e) => format!("Camera is not available: {e}"),
222            Self::CameraPermissionDenied(e) => format!("Camera permission was denied: {e}"),
223            Self::CameraStalled => "The camera feed stopped responding; try again".into(),
224            Self::NotJsonObject(e) => format!("Expected JSON object, got: {e}"),
225            #[cfg(feature = "zip")]
226            Self::Archive(e) => format!("Archive error: {e}"),
227            Self::Worker(e) => format!("Background task error: {e}"),
228            Self::FileTooLarge { name, size, limit } => {
229                format!("File too large ({name}: {size} bytes, limit {limit} bytes)")
230            }
231            Self::Cancelled => "Operation cancelled".into(),
232            #[cfg(target_os = "android")]
233            Self::JNI(e) => format!("JNI error: {e}"),
234        }
235    }
236
237    fn render_spa(&self) -> String {
238        match self {
239            Self::IO(e) => format!("Error de E/S: {e}"),
240            Self::Json(e) => format!("Error de análisis JSON: {e}"),
241            Self::Base64(e) => format!("Error de decodificación Base64: {e}"),
242            #[cfg(feature = "qr")]
243            Self::Qr(e) => format!("Error de código QR: {e}"),
244            Self::Env(e) => format!("Error de variable de entorno: {e}"),
245            Self::Channel(e) => format!("Error de recepción en canal: {e}"),
246            Self::JS(e) => format!("Error de evaluación JavaScript: {e}"),
247            Self::QrNotFound => "No se encontró ningún QR en la imagen".into(),
248            Self::EvalFinished => {
249                "Se perdió la conexión con el navegador; inténtalo de nuevo".into()
250            }
251            #[cfg(feature = "crypto")]
252            Self::Cipher(e) => format!("Error de inicialización de cifrado: {e}"),
253            #[cfg(feature = "crypto")]
254            Self::KeyDerive(e) => format!("Error de derivación de clave: {e}"),
255            #[cfg(feature = "crypto")]
256            Self::Getrandom(e) => format!("Error de generación de números aleatorios: {e}"),
257            #[cfg(feature = "crypto")]
258            Self::Encrypt(e) => format!("Falló el cifrado: {e}"),
259            #[cfg(feature = "crypto")]
260            Self::Decrypt(e) => format!("Falló el descifrado: {e}"),
261            Self::InvalidFormat(e) => format!("Formato de carga útil cifrada no válido: {e}"),
262            Self::Convert { context, source } => {
263                format!("Error de conversión numérica ({context}): {source}")
264            }
265            Self::CameraNotAvailable(e) => format!("La cámara no está disponible: {e}"),
266            Self::CameraPermissionDenied(e) => format!("Permiso de cámara denegado: {e}"),
267            Self::CameraStalled => "La cámara dejó de responder; inténtalo de nuevo".into(),
268            Self::NotJsonObject(e) => format!("Se esperaba un objeto JSON, se obtuvo: {e}"),
269            #[cfg(feature = "zip")]
270            Self::Archive(e) => format!("Error de archivo: {e}"),
271            Self::Worker(e) => {
272                format!("La tarea en segundo plano se detuvo inesperadamente (error: {e})")
273            }
274            Self::FileTooLarge { name, size, limit } => {
275                format!("Archivo demasiado grande ({name}: {size} bytes, límite {limit} bytes)")
276            }
277            Self::Cancelled => "Operación cancelada".into(),
278            #[cfg(target_os = "android")]
279            Self::JNI(e) => format!("Error JNI: {e}"),
280        }
281    }
282
283    fn render_rus(&self) -> String {
284        match self {
285            Self::IO(e) => format!("Ошибка ввода-вывода: {e}"),
286            Self::Json(e) => format!("Ошибка разбора JSON: {e}"),
287            Self::Base64(e) => format!("Ошибка декодирования Base64: {e}"),
288            #[cfg(feature = "qr")]
289            Self::Qr(e) => format!("Ошибка QR-кода: {e}"),
290            Self::Env(e) => format!("Ошибка переменной окружения: {e}"),
291            Self::Channel(e) => format!("Ошибка получения из канала: {e}"),
292            Self::JS(e) => format!("Ошибка выполнения JavaScript: {e}"),
293            Self::QrNotFound => "QR-код не найден на изображении".into(),
294            Self::EvalFinished => "Соединение с браузером потеряно; попробуйте ещё раз".into(),
295            #[cfg(feature = "crypto")]
296            Self::Cipher(e) => format!("Ошибка инициализации шифра: {e}"),
297            #[cfg(feature = "crypto")]
298            Self::KeyDerive(e) => format!("Ошибка вывода ключа: {e}"),
299            #[cfg(feature = "crypto")]
300            Self::Getrandom(e) => format!("Ошибка генерации случайных чисел: {e}"),
301            #[cfg(feature = "crypto")]
302            Self::Encrypt(e) => format!("Ошибка шифрования: {e}"),
303            #[cfg(feature = "crypto")]
304            Self::Decrypt(e) => format!("Ошибка расшифровки: {e}"),
305            Self::InvalidFormat(e) => format!("Неверный формат зашифрованных данных: {e}"),
306            Self::Convert { context, source } => {
307                format!("Ошибка численного преобразования ({context}): {source}")
308            }
309            Self::CameraNotAvailable(e) => format!("Камера недоступна: {e}"),
310            Self::CameraPermissionDenied(e) => format!("Разрешение на камеру отклонено: {e}"),
311            Self::CameraStalled => "Поток с камеры остановился; попробуйте ещё раз".into(),
312            Self::NotJsonObject(e) => format!("Ожидался JSON-объект, получено: {e}"),
313            #[cfg(feature = "zip")]
314            Self::Archive(e) => format!("Ошибка архива: {e}"),
315            Self::Worker(e) => format!("Ошибка фоновой задачи: {e}"),
316            Self::FileTooLarge { name, size, limit } => {
317                format!("Файл слишком большой ({name}: {size} байт, лимит {limit} байт)")
318            }
319            Self::Cancelled => "Операция отменена".into(),
320            #[cfg(target_os = "android")]
321            Self::JNI(e) => format!("Ошибка JNI: {e}"),
322        }
323    }
324}