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 closed before completion")]
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    #[error("Required object unavailable: {0}")]
144    Missing(Missing),
145    #[error("{0} is unavailable: web feature disabled")]
146    CapabilityDisabled(Capability),
147    #[error("Clipboard error: {0}")]
148    Clipboard(ClipboardError),
149    #[cfg(target_arch = "wasm32")]
150    #[error("JavaScript operation failed: {0}")]
151    Js(JsError),
152    #[error("File picker timed out")]
153    FilePickerTimedOut,
154    #[error("File picker failed")]
155    FilePickerFailed,
156    #[error("Save was cancelled")]
157    SaveCancelled,
158    #[error("xdg-open failed for {url}")]
159    OpenUrlFailed { url: String },
160    #[error("xdg-open timed out for {url}")]
161    OpenUrlTimedOut { url: String },
162    #[error("Share failed: {0}")]
163    ShareFailed(Box<Error>),
164}
165
166/// A browser object, platform handle, or storage location the operation
167/// requires, but which the current platform or build does not provide.
168#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
169pub enum Missing {
170    #[error("window")]
171    Window,
172    #[error("document")]
173    Document,
174    #[error("document body")]
175    Body,
176    #[error("video element")]
177    VideoElement,
178    #[error("canvas")]
179    Canvas,
180    #[error("2D context")]
181    Context2d,
182    #[error("localStorage")]
183    LocalStorage,
184    #[error("anchor element")]
185    Anchor,
186    #[error("input element")]
187    Input,
188    #[error("file entry")]
189    FileEntry,
190    #[error("clipboard text")]
191    ClipboardText,
192    #[error("desktop session")]
193    DesktopSession,
194    #[error("Android application")]
195    AndroidApp,
196    #[error("data directory")]
197    DataDir,
198}
199
200/// A capability that the current build does not enable.
201#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
202pub enum Capability {
203    #[error("clipboard")]
204    Clipboard,
205    #[error("share")]
206    Share,
207    #[error("save")]
208    Save,
209}
210
211/// A clipboard that exists but refused the operation.
212#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
213pub enum ClipboardError {
214    #[error("unavailable")]
215    Unavailable,
216    #[error("busy")]
217    Busy,
218    #[error("content unavailable")]
219    ContentUnavailable,
220    #[error("conversion failed")]
221    ConversionFailed,
222    #[error("{0}")]
223    Unknown(String),
224}
225
226/// A JavaScript value rejected by a Web API call, kept alive so that its
227/// original payload stays inspectable.
228#[cfg(target_arch = "wasm32")]
229#[derive(Debug, Clone, thiserror::Error)]
230#[error("{0:?}")]
231pub struct JsError(pub Arc<web_sys::wasm_bindgen::JsValue>);
232
233#[cfg(target_arch = "wasm32")]
234impl PartialEq for JsError {
235    fn eq(&self, other: &Self) -> bool {
236        Arc::ptr_eq(&self.0, &other.0)
237    }
238}
239
240#[cfg(target_arch = "wasm32")]
241impl Eq for JsError {}
242
243#[cfg(target_arch = "wasm32")]
244impl From<web_sys::wasm_bindgen::JsValue> for JsError {
245    fn from(e: web_sys::wasm_bindgen::JsValue) -> Self {
246        Self(Arc::new(e))
247    }
248}
249
250#[cfg(target_arch = "wasm32")]
251impl From<web_sys::wasm_bindgen::JsValue> for Error {
252    fn from(e: web_sys::wasm_bindgen::JsValue) -> Self {
253        Self::Js(JsError::from(e))
254    }
255}
256
257#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
258#[error("Background task stopped unexpectedly")]
259pub struct WorkerStopped;
260
261impl From<std::io::Error> for Error {
262    fn from(e: std::io::Error) -> Self {
263        Error::IO(IoError::from(e))
264    }
265}
266
267impl From<serde_json::Error> for Error {
268    fn from(e: serde_json::Error) -> Self {
269        Error::Json(JsonError::from(e))
270    }
271}
272
273impl From<base64::DecodeError> for Error {
274    fn from(e: base64::DecodeError) -> Self {
275        Error::Base64(e)
276    }
277}
278
279#[cfg(feature = "crypto")]
280impl From<cipher::InvalidLength> for Error {
281    fn from(e: cipher::InvalidLength) -> Self {
282        Error::Cipher(e)
283    }
284}
285
286#[cfg(target_os = "android")]
287impl From<jni::errors::Error> for Error {
288    fn from(e: jni::errors::Error) -> Self {
289        Error::JNI(JniError::from(e))
290    }
291}
292
293impl From<WorkerStopped> for Error {
294    fn from(e: WorkerStopped) -> Self {
295        Error::Worker(e)
296    }
297}
298
299#[cfg(feature = "zip")]
300impl From<zip::result::ZipError> for Error {
301    fn from(e: zip::result::ZipError) -> Self {
302        Error::Archive(ZipErr::from(e))
303    }
304}
305
306impl I18N for Error {
307    fn render_eng(&self) -> String {
308        match self {
309            Self::IO(e) => format!("IO error: {e}"),
310            Self::Json(e) => format!("JSON parsing error: {e}"),
311            Self::Base64(e) => format!("Base64 decoding error: {e}"),
312            #[cfg(feature = "qr")]
313            Self::Qr(e) => format!("QR code error: {e}"),
314            Self::Env(e) => format!("Environment variable error: {e}"),
315            Self::Channel(e) => format!("Channel receive error: {e}"),
316            Self::JS(e) => format!("JavaScript evaluation error: {e}"),
317            Self::QrNotFound => "No QR found in image".into(),
318            Self::EvalFinished => "The connection to the browser was lost; please try again".into(),
319            #[cfg(feature = "crypto")]
320            Self::Cipher(e) => format!("Cipher initialization error: {e}"),
321            #[cfg(feature = "crypto")]
322            Self::KeyDerive(e) => format!("Key derivation error: {e}"),
323            #[cfg(feature = "crypto")]
324            Self::Getrandom(e) => format!("Random number generation error: {e}"),
325            #[cfg(feature = "crypto")]
326            Self::Encrypt(e) => format!("Encryption failed: {e}"),
327            #[cfg(feature = "crypto")]
328            Self::Decrypt(e) => format!("Decryption failed: {e}"),
329            Self::InvalidFormat(e) => format!("Invalid encrypted payload format: {e}"),
330            Self::Convert { context, source } => {
331                format!("Numeric conversion failed ({context}): {source}")
332            }
333            Self::CameraNotAvailable(e) => format!("Camera is not available: {e}"),
334            Self::CameraPermissionDenied(e) => format!("Camera permission was denied: {e}"),
335            Self::CameraStalled => "The camera feed stopped responding; try again".into(),
336            Self::NotJsonObject(e) => format!("Expected JSON object, got: {e}"),
337            #[cfg(feature = "zip")]
338            Self::Archive(e) => format!("Archive error: {e}"),
339            Self::Worker(e) => format!("Background task error: {e}"),
340            Self::FileTooLarge { name, size, limit } => {
341                format!("File too large ({name}: {size} bytes, limit {limit} bytes)")
342            }
343            Self::Cancelled => "Operation cancelled".into(),
344            Self::Missing(m) => format!("Required object unavailable: {m}"),
345            Self::CapabilityDisabled(c) => format!("{c} is unavailable: web feature disabled"),
346            Self::Clipboard(e) => format!("Clipboard error: {e}"),
347            #[cfg(target_arch = "wasm32")]
348            Self::Js(e) => format!("JavaScript operation failed: {e}"),
349            Self::FilePickerTimedOut => "File picker timed out".into(),
350            Self::FilePickerFailed => "File picker failed".into(),
351            Self::SaveCancelled => "Save was cancelled".into(),
352            Self::OpenUrlFailed { url } => format!("xdg-open failed for {url}"),
353            Self::OpenUrlTimedOut { url } => format!("xdg-open timed out for {url}"),
354            #[cfg(target_os = "android")]
355            Self::JNI(e) => format!("JNI error: {e}"),
356            Self::ShareFailed(e) => format!("Share failed: {e}"),
357        }
358    }
359
360    fn render_spa(&self) -> String {
361        match self {
362            Self::IO(e) => format!("Error de E/S: {e}"),
363            Self::Json(e) => format!("Error de análisis JSON: {e}"),
364            Self::Base64(e) => format!("Error de decodificación Base64: {e}"),
365            #[cfg(feature = "qr")]
366            Self::Qr(e) => format!("Error de código QR: {e}"),
367            Self::Env(e) => format!("Error de variable de entorno: {e}"),
368            Self::Channel(e) => format!("Error de recepción en canal: {e}"),
369            Self::JS(e) => format!("Error de evaluación JavaScript: {e}"),
370            Self::QrNotFound => "No se encontró ningún QR en la imagen".into(),
371            Self::EvalFinished => {
372                "Se perdió la conexión con el navegador; inténtalo de nuevo".into()
373            }
374            #[cfg(feature = "crypto")]
375            Self::Cipher(e) => format!("Error de inicialización de cifrado: {e}"),
376            #[cfg(feature = "crypto")]
377            Self::KeyDerive(e) => format!("Error de derivación de clave: {e}"),
378            #[cfg(feature = "crypto")]
379            Self::Getrandom(e) => format!("Error de generación de números aleatorios: {e}"),
380            #[cfg(feature = "crypto")]
381            Self::Encrypt(e) => format!("Falló el cifrado: {e}"),
382            #[cfg(feature = "crypto")]
383            Self::Decrypt(e) => format!("Falló el descifrado: {e}"),
384            Self::InvalidFormat(e) => format!("Formato de carga útil cifrada no válido: {e}"),
385            Self::Convert { context, source } => {
386                format!("Error de conversión numérica ({context}): {source}")
387            }
388            Self::CameraNotAvailable(e) => format!("La cámara no está disponible: {e}"),
389            Self::CameraPermissionDenied(e) => format!("Permiso de cámara denegado: {e}"),
390            Self::CameraStalled => "La cámara dejó de responder; inténtalo de nuevo".into(),
391            Self::NotJsonObject(e) => format!("Se esperaba un objeto JSON, se obtuvo: {e}"),
392            #[cfg(feature = "zip")]
393            Self::Archive(e) => format!("Error de archivo: {e}"),
394            Self::Worker(e) => {
395                format!("La tarea en segundo plano se detuvo inesperadamente (error: {e})")
396            }
397            Self::FileTooLarge { name, size, limit } => {
398                format!("Archivo demasiado grande ({name}: {size} bytes, límite {limit} bytes)")
399            }
400            Self::Cancelled => "Operación cancelada".into(),
401            Self::Missing(m) => format!("Objeto requerido no disponible: {m}"),
402            Self::CapabilityDisabled(c) => {
403                format!("{c} no está disponible: función web deshabilitada")
404            }
405            Self::Clipboard(e) => format!("Error de portapapeles: {e}"),
406            #[cfg(target_arch = "wasm32")]
407            Self::Js(e) => format!("La operación JavaScript falló: {e}"),
408            Self::FilePickerTimedOut => "El selector de archivos agotó el tiempo de espera".into(),
409            Self::FilePickerFailed => "El selector de archivos falló".into(),
410            Self::SaveCancelled => "Se canceló el guardado".into(),
411            Self::OpenUrlFailed { url } => format!("xdg-open falló al abrir {url}"),
412            Self::OpenUrlTimedOut { url } => format!("xdg-open agotó el tiempo para {url}"),
413            #[cfg(target_os = "android")]
414            Self::JNI(e) => format!("Error JNI: {e}"),
415            Self::ShareFailed(e) => format!("Falló al compartir: {e}"),
416        }
417    }
418
419    fn render_rus(&self) -> String {
420        match self {
421            Self::IO(e) => format!("Ошибка ввода-вывода: {e}"),
422            Self::Json(e) => format!("Ошибка разбора JSON: {e}"),
423            Self::Base64(e) => format!("Ошибка декодирования Base64: {e}"),
424            #[cfg(feature = "qr")]
425            Self::Qr(e) => format!("Ошибка QR-кода: {e}"),
426            Self::Env(e) => format!("Ошибка переменной окружения: {e}"),
427            Self::Channel(e) => format!("Ошибка получения из канала: {e}"),
428            Self::JS(e) => format!("Ошибка выполнения JavaScript: {e}"),
429            Self::QrNotFound => "QR-код не найден на изображении".into(),
430            Self::EvalFinished => "Соединение с браузером потеряно; попробуйте ещё раз".into(),
431            #[cfg(feature = "crypto")]
432            Self::Cipher(e) => format!("Ошибка инициализации шифра: {e}"),
433            #[cfg(feature = "crypto")]
434            Self::KeyDerive(e) => format!("Ошибка вывода ключа: {e}"),
435            #[cfg(feature = "crypto")]
436            Self::Getrandom(e) => format!("Ошибка генерации случайных чисел: {e}"),
437            #[cfg(feature = "crypto")]
438            Self::Encrypt(e) => format!("Ошибка шифрования: {e}"),
439            #[cfg(feature = "crypto")]
440            Self::Decrypt(e) => format!("Ошибка расшифровки: {e}"),
441            Self::InvalidFormat(e) => format!("Неверный формат зашифрованных данных: {e}"),
442            Self::Convert { context, source } => {
443                format!("Ошибка численного преобразования ({context}): {source}")
444            }
445            Self::CameraNotAvailable(e) => format!("Камера недоступна: {e}"),
446            Self::CameraPermissionDenied(e) => format!("Разрешение на камеру отклонено: {e}"),
447            Self::CameraStalled => "Поток с камеры остановился; попробуйте ещё раз".into(),
448            Self::NotJsonObject(e) => format!("Ожидался JSON-объект, получено: {e}"),
449            #[cfg(feature = "zip")]
450            Self::Archive(e) => format!("Ошибка архива: {e}"),
451            Self::Worker(e) => format!("Ошибка фоновой задачи: {e}"),
452            Self::FileTooLarge { name, size, limit } => {
453                format!("Файл слишком большой ({name}: {size} байт, лимит {limit} байт)")
454            }
455            Self::Cancelled => "Операция отменена".into(),
456            Self::Missing(m) => format!("Требуемый объект недоступен: {m}"),
457            Self::CapabilityDisabled(c) => format!("{c} недоступна: веб-функция отключена"),
458            Self::Clipboard(e) => format!("Ошибка буфера обмена: {e}"),
459            #[cfg(target_arch = "wasm32")]
460            Self::Js(e) => format!("Операция JavaScript не выполнена: {e}"),
461            Self::FilePickerTimedOut => "Выбор файла: время ожидания истекло".into(),
462            Self::FilePickerFailed => "Не удалось выбрать файл".into(),
463            Self::SaveCancelled => "Сохранение отменено".into(),
464            Self::OpenUrlFailed { url } => format!("xdg-open не смог открыть {url}"),
465            Self::OpenUrlTimedOut { url } => format!("xdg-open превысил время ожидания для {url}"),
466            #[cfg(target_os = "android")]
467            Self::JNI(e) => format!("Ошибка JNI: {e}"),
468            Self::ShareFailed(e) => format!("Не удалось поделиться: {e}"),
469        }
470    }
471}