1use camera::{BackendId, CameraErrorKind, OperationStage, RecoveryHint};
2use serde_json::json;
3use thiserror::Error;
4
5#[non_exhaustive]
7#[derive(Debug, Error)]
8pub enum CameraError {
9 #[error(transparent)]
11 Camera(#[from] camera::CameraError),
12 #[error("JNI: {0}")]
14 Jni(#[from] jni::errors::Error),
15 #[error("Android adapter: {message}")]
17 Adapter {
18 kind: CameraErrorKind,
20 recovery_hint: RecoveryHint,
22 message: String,
24 },
25 #[error("Android I/O: {0}")]
27 Io(#[from] std::io::Error),
28}
29
30impl CameraError {
31 pub fn adapter(kind: CameraErrorKind, message: impl Into<String>) -> Self {
33 Self::Adapter {
34 kind,
35 recovery_hint: RecoveryHint::None,
36 message: message.into(),
37 }
38 }
39
40 pub fn kind(&self) -> CameraErrorKind {
42 match self {
43 Self::Camera(error) => error.kind(),
44 Self::Jni(_) => CameraErrorKind::BackendFailure,
45 Self::Adapter { kind, .. } => *kind,
46 Self::Io(_) => CameraErrorKind::Io,
47 }
48 }
49
50 pub fn code(&self) -> &'static str {
52 self.kind().as_str()
53 }
54
55 pub fn recovery_hint(&self) -> RecoveryHint {
57 match self {
58 Self::Camera(error) => error.recovery_hint(),
59 Self::Jni(_) | Self::Adapter { .. } => RecoveryHint::None,
60 Self::Io(_) => RecoveryHint::Retry,
61 }
62 }
63
64 pub fn is_retryable(&self) -> bool {
66 self.recovery_hint().is_retryable()
67 }
68
69 pub fn backend(&self) -> Option<&BackendId> {
71 match self {
72 Self::Camera(error) => error.backend(),
73 _ => None,
74 }
75 }
76
77 pub fn stage(&self) -> Option<OperationStage> {
79 match self {
80 Self::Camera(error) => error.stage(),
81 Self::Jni(_) | Self::Adapter { .. } => Some(OperationStage::BackendCommand),
82 Self::Io(_) => Some(OperationStage::Open),
83 }
84 }
85
86 pub fn native_code(&self) -> Option<i64> {
88 match self {
89 Self::Camera(error) => error.native_code(),
90 Self::Io(error) => error.raw_os_error().map(i64::from),
91 _ => None,
92 }
93 }
94
95 pub fn boundary_payload(&self) -> String {
98 json!({
99 "schemaVersion": 1,
100 "code": self.code(),
101 "recovery": self.recovery_hint().as_str(),
102 "backend": self.backend().map(BackendId::as_str),
103 "stage": self.stage().map(OperationStage::as_str),
104 "nativeCode": self.native_code(),
105 "message": self.to_string(),
106 })
107 .to_string()
108 }
109}
110
111pub type Result<T> = std::result::Result<T, CameraError>;