file_storage/error/
error.rs1use crate::StoragePath;
2use crate::{Operation, Reason};
3use std::fmt::{Display, Formatter};
4use std::io;
5use std::io::ErrorKind;
6use std::path::Path;
7
8#[derive(Debug)]
10pub struct Error {
11 path: StoragePath,
12 operation: Operation,
13 reason: Reason,
14 source: Option<io::Error>,
15}
16
17impl Error {
18 pub fn new<P>(path: P, operation: Operation, reason: Reason) -> Self
24 where
25 P: Into<StoragePath>,
26 {
27 let path: StoragePath = path.into();
28 Self {
29 path,
30 operation,
31 reason,
32 source: None,
33 }
34 }
35
36 pub fn from_source<P, E>(path: P, operation: Operation, source: E) -> Self
40 where
41 P: Into<StoragePath>,
42 E: Into<io::Error>,
43 {
44 let path: StoragePath = path.into();
45 Self {
46 path,
47 operation,
48 reason: Reason::Other,
49 source: Some(source.into()),
50 }
51 }
52
53 pub fn from_message<P, S>(path: P, operation: Operation, message: S) -> Self
58 where
59 P: Into<StoragePath>,
60 S: Into<String>,
61 {
62 Error::from_source(path, operation, io::Error::other(message.into()))
63 }
64}
65
66impl Error {
67 pub fn unknown_file_system(path: &str) -> io::Error {
74 io::Error::other(format!("unknown file system for path: {}", path))
75 }
76
77 pub fn path_not_utf8(path: &Path) -> io::Error {
79 io::Error::new(
80 ErrorKind::InvalidInput,
81 format!("path not utf-8: {:?}", path),
82 )
83 }
84}
85
86impl Error {
87 pub fn path(&self) -> &StoragePath {
91 &self.path
92 }
93
94 pub fn export_path(self) -> StoragePath {
96 self.path
97 }
98
99 pub fn operation(&self) -> Operation {
101 self.operation
102 }
103
104 pub fn reason(&self) -> Reason {
106 self.reason
107 }
108
109 pub fn io_source(&self) -> Option<&io::Error> {
111 self.source.as_ref()
112 }
113}
114
115impl From<Error> for io::Error {
116 fn from(error: Error) -> Self {
117 let kind: ErrorKind = match error.reason() {
118 Reason::UnknownFileSystem => ErrorKind::Unsupported,
119 Reason::UnsupportedOperation => ErrorKind::Unsupported,
120 Reason::FileNotFound => ErrorKind::NotFound,
121 Reason::FileAlreadyExists => ErrorKind::AlreadyExists,
122 Reason::FileContentNotUTF8 => ErrorKind::InvalidData,
123 Reason::InvalidPath => ErrorKind::InvalidInput,
124 Reason::Other => ErrorKind::Other,
125 };
126 Self::new(kind, error)
127 }
128}
129
130impl Display for Error {
131 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
132 let file_or_folder: &str = if self.path.is_file() {
133 "file"
134 } else {
135 "folder"
136 };
137 write!(
138 f,
139 "{} error: op={} path={}",
140 file_or_folder, self.operation, self.path
141 )?;
142 if let Some(source) = self.io_source() {
143 write!(f, " source={}", source)?;
144 } else {
145 write!(f, " reason={}", self.reason)?;
146 }
147 Ok(())
148 }
149}
150
151impl std::error::Error for Error {
152 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
153 self.source.as_ref().map(|e| e as &(dyn std::error::Error + 'static))
154 }
155}