Skip to main content

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    /// Another open connection is blocking the request.
18    Blocked,
19}
20
21impl From<std::io::Error> for Error {
22    fn from(other: std::io::Error) -> Self {
23        Self::Generic(other.to_string())
24    }
25}
26
27impl std::error::Error for Error {
28    fn description(&self) -> &str {
29        match *self {
30            Error::WindowNotAvailable => "Accessing a Window has failed",
31            Error::NotSupported(_) => "IndexedDB is not supported by your browser",
32            Error::Generic(_) => "The database returned a generic error",
33            Error::Blocked => "Another open connection is blocking the request",
34            Error::Canceled => "The operation was canceled",
35        }
36    }
37}
38
39impl fmt::Display for Error {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        match *self {
42            Error::WindowNotAvailable => write!(f, "Accessing a Window has failed"),
43            Error::NotSupported(ref err) => {
44                write!(f, "IndexedDB is not supported by your browser: {}", err,)
45            }
46            Error::Generic(ref err) => {
47                write!(f, "Generic error: {}", err,)
48            }
49            Error::Canceled => write!(f, "The operation was canceled"),
50            Error::Blocked => write!(f, "Another open connection is blocking the request"),
51        }
52    }
53}
54
55pub(crate) fn io_err_string<T: ToString>(e: T) -> std::io::Error {
56    std::io::Error::other(e.to_string())
57}
58
59pub(crate) fn io_err_jsvalue(e: JsValue) -> std::io::Error {
60    std::io::Error::other(e.as_string().unwrap_or_default())
61}
62
63pub(crate) fn bad_cast_io_err(context: &str, v: JsValue) -> std::io::Error {
64    io_err_string(format!("{} is a {:?}", context, v))
65}
66pub(crate) fn bad_cast_generic(context: &str, v: JsValue) -> Error {
67    Error::Generic(format!("{} is a {:?}", context, v))
68}