keyvaluedb_web/
error.rs

1//! Errors that can occur when working with IndexedDB.
2
3use std::fmt;
4use wasm_bindgen::JsValue;
5
6/// An error that occurred when working with IndexedDB.
7#[derive(Clone, PartialEq, Debug)]
8pub enum Error {
9    /// Accessing a Window has failed.
10    WindowNotAvailable,
11    /// IndexedDB is not supported by your browser.
12    NotSupported(String),
13    /// The database returned a generic error.
14    Generic(String),
15    /// The operation was canceled
16    Canceled,
17}
18
19impl From<std::io::Error> for Error {
20    fn from(other: std::io::Error) -> Self {
21        Self::Generic(other.to_string())
22    }
23}
24
25impl std::error::Error for Error {
26    fn description(&self) -> &str {
27        match *self {
28            Error::WindowNotAvailable => "Accessing a Window has failed",
29            Error::NotSupported(_) => "IndexedDB is not supported by your browser",
30            Error::Generic(_) => "The database returned a generic error",
31            Error::Canceled => "The operation was canceled",
32        }
33    }
34}
35
36impl fmt::Display for Error {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match *self {
39            Error::WindowNotAvailable => write!(f, "Accessing a Window has failed"),
40            Error::NotSupported(ref err) => {
41                write!(f, "IndexedDB is not supported by your browser: {}", err,)
42            }
43            Error::Generic(ref err) => {
44                write!(f, "Generic error: {}", err,)
45            }
46            Error::Canceled => write!(f, "The operation was canceled"),
47        }
48    }
49}
50
51pub(crate) fn io_err_string<T: ToString>(e: T) -> std::io::Error {
52    std::io::Error::new(std::io::ErrorKind::Other, e.to_string())
53}
54
55pub(crate) fn io_err_jsvalue(e: JsValue) -> std::io::Error {
56    std::io::Error::new(std::io::ErrorKind::Other, e.as_string().unwrap_or_default())
57}
58
59pub(crate) fn bad_cast_io_err(context: &str, v: JsValue) -> std::io::Error {
60    io_err_string(format!("{} is a {:?}", context, v))
61}
62pub(crate) fn bad_cast_generic(context: &str, v: JsValue) -> Error {
63    Error::Generic(format!("{} is a {:?}", context, v))
64}