simplify error handling

This commit is contained in:
Jonas Kruckenberg 2022-11-13 21:19:00 +01:00
parent e431dc89a8
commit bd652c956f
8 changed files with 94 additions and 147 deletions

View file

@ -10,7 +10,7 @@ pub async fn get_name() -> anyhow::Result<()> {
}
pub async fn get_version() -> anyhow::Result<()> {
let version = app::get_version().await;
let version = app::get_version().await?;
ensure!(version.major == 0);
ensure!(version.minor == 0);

View file

@ -4,7 +4,7 @@ use tauri_sys::clipboard;
pub async fn test() -> anyhow::Result<()> {
clipboard::write_text("foobar").await;
let text = clipboard::read_text().await;
let text = clipboard::read_text().await?;
ensure!(text == Some("foobar".to_string()));

View file

@ -1,7 +1,5 @@
use semver::Version;
use crate::Error;
/// Gets the application name.
///
/// # Example
@ -12,7 +10,7 @@ use crate::Error;
/// ```
#[inline(always)]
pub async fn get_name() -> crate::Result<String> {
let js_val = inner::getName().await.map_err(Error::Other)?;
let js_val = inner::getName().await?;
Ok(serde_wasm_bindgen::from_value(js_val)?)
}
@ -28,7 +26,7 @@ pub async fn get_name() -> crate::Result<String> {
/// ```
#[inline(always)]
pub async fn get_version() -> crate::Result<Version> {
let js_val = inner::getVersion().await.map_err(Error::Other)?;
let js_val = inner::getVersion().await?;
Ok(serde_wasm_bindgen::from_value(js_val)?)
}
@ -44,7 +42,7 @@ pub async fn get_version() -> crate::Result<Version> {
/// ```
#[inline(always)]
pub async fn get_tauri_version() -> crate::Result<Version> {
let js_val = inner::getTauriVersion().await.map_err(Error::Other)?;
let js_val = inner::getTauriVersion().await?;
Ok(serde_wasm_bindgen::from_value(js_val)?)
}
@ -60,7 +58,7 @@ pub async fn get_tauri_version() -> crate::Result<Version> {
/// ```
#[inline(always)]
pub async fn show() -> crate::Result<()> {
inner::show().await.map_err(Error::Other)
Ok(inner::show().await?)
}
/// Hides the application on macOS.
@ -74,7 +72,7 @@ pub async fn show() -> crate::Result<()> {
/// ```
#[inline(always)]
pub async fn hide() -> crate::Result<()> {
inner::hide().await.map_err(Error::Other)
Ok(inner::hide().await?)
}
mod inner {

View file

@ -1,5 +1,3 @@
use crate::Error;
/// Gets the clipboard content as plain text.
///
/// # Example
@ -11,7 +9,7 @@ use crate::Error;
/// ```
#[inline(always)]
pub async fn read_text() -> crate::Result<String> {
let js_val = inner::readText().await.map_err(Error::Other)?;
let js_val = inner::readText().await?;
Ok(serde_wasm_bindgen::from_value(js_val)?)
}
@ -30,7 +28,7 @@ pub async fn read_text() -> crate::Result<String> {
/// @returns A promise indicating the success or failure of the operation.
#[inline(always)]
pub async fn write_text(text: &str) -> crate::Result<()> {
inner::writeText(text).await.map_err(Error::Other)
Ok(inner::writeText(text).await?)
}
mod inner {

View file

@ -1,10 +1,7 @@
use std::fmt::Debug;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use wasm_bindgen::{prelude::Closure, JsValue};
use crate::Error;
#[derive(Deserialize)]
pub struct Event<T> {
/// Event name
@ -49,8 +46,9 @@ impl<T: Debug> Debug for Event<T> {
#[inline(always)]
pub async fn emit<T: Serialize>(event: &str, payload: &T) -> crate::Result<()> {
inner::emit(event, serde_wasm_bindgen::to_value(payload)?)
.await
.map_err(Error::Other)
.await?;
Ok(())
}
/// Listen to an event from the backend.
@ -83,7 +81,7 @@ where
(handler)(serde_wasm_bindgen::from_value(raw).unwrap())
});
let unlisten = inner::listen(event, &closure).await.map_err(Error::Other)?;
let unlisten = inner::listen(event, &closure).await?;
closure.forget();
@ -128,7 +126,7 @@ where
(handler)(serde_wasm_bindgen::from_value(raw).unwrap())
});
let unlisten = inner::once(event, &closure).await.map_err(Error::Other)?;
let unlisten = inner::once(event, &closure).await?;
closure.forget();

View file

@ -17,16 +17,28 @@ pub mod window;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
Serde(#[from] serde_wasm_bindgen::Error),
#[error("{0}")]
Serde(String),
#[error("Unknown Theme \"{0}\". Expected one of \"light\",\"dark\"")]
UnknownTheme(String),
#[error("Invalid Url {0}")]
InvalidUrl(#[from] url::ParseError),
#[error("Invalid Version {0}")]
InvalidVersion(#[from] semver::Error),
#[error("{0:?}")]
Other(JsValue),
#[error("{0}")]
Other(String),
}
impl From<serde_wasm_bindgen::Error> for Error {
fn from(e: serde_wasm_bindgen::Error) -> Self {
Self::Serde(format!("{:?}", e))
}
}
impl From<JsValue> for Error {
fn from(e: JsValue) -> Self {
Self::Serde(format!("{:?}", e))
}
}
pub(crate) type Result<T> = std::result::Result<T, Error>;

View file

@ -1,8 +1,6 @@
use serde::{de::DeserializeOwned, Serialize};
use url::Url;
use crate::Error;
/// Convert a device file path to an URL that can be loaded by the webview.
/// Note that `asset:` and `https://asset.localhost` must be added to [`tauri.security.csp`](https://tauri.app/v1/api/config/#securityconfig.csp) in `tauri.conf.json`.
/// Example CSP value: `"csp": "default-src 'self'; img-src 'self' asset: https://asset.localhost"` to use the asset protocol on image sources.
@ -39,9 +37,7 @@ use crate::Error;
/// @return the URL that can be used as source on the webview.
#[inline(always)]
pub async fn convert_file_src(file_path: &str, protocol: Option<&str>) -> crate::Result<Url> {
let js_val = inner::convertFileSrc(file_path, protocol)
.await
.map_err(Error::Other)?;
let js_val = inner::convertFileSrc(file_path, protocol).await?;
Ok(serde_wasm_bindgen::from_value(js_val)?)
}
@ -66,9 +62,7 @@ pub async fn convert_file_src(file_path: &str, protocol: Option<&str>) -> crate:
/// @return A promise resolving or rejecting to the backend response.
#[inline(always)]
pub async fn invoke<A: Serialize, R: DeserializeOwned>(cmd: &str, args: &A) -> crate::Result<R> {
let raw = inner::invoke(cmd, serde_wasm_bindgen::to_value(args)?)
.await
.map_err(crate::Error::Other)?;
let raw = inner::invoke(cmd, serde_wasm_bindgen::to_value(args)?).await?;
serde_wasm_bindgen::from_value(raw).map_err(Into::into)
}
@ -86,8 +80,7 @@ pub async fn transform_callback<T: DeserializeOwned>(
&|raw| callback(serde_wasm_bindgen::from_value(raw).unwrap()),
once,
)
.await
.map_err(Error::Other)?;
.await?;
Ok(serde_wasm_bindgen::from_value(js_val)?)
}

View file

@ -136,83 +136,63 @@ impl WebviewWindow {
}
pub async fn scale_factor(&self) -> crate::Result<f64> {
let js_val = self.0.scaleFactor().await.map_err(Error::Other)?;
let js_val = self.0.scaleFactor().await?;
Ok(serde_wasm_bindgen::from_value(js_val)?)
}
pub async fn inner_position(&self) -> crate::Result<PhysicalPosition> {
Ok(PhysicalPosition(
self.0
.innerPosition()
.await
.map_err(Error::Other)?
.unchecked_into(),
self.0.innerPosition().await?.unchecked_into(),
))
}
pub async fn outer_position(&self) -> crate::Result<PhysicalPosition> {
Ok(PhysicalPosition(
self.0
.outerPosition()
.await
.map_err(Error::Other)?
.unchecked_into(),
self.0.outerPosition().await?.unchecked_into(),
))
}
pub async fn inner_size(&self) -> crate::Result<PhysicalSize> {
Ok(PhysicalSize(
self.0
.innerSize()
.await
.map_err(Error::Other)?
.unchecked_into(),
))
Ok(PhysicalSize(self.0.innerSize().await?.unchecked_into()))
}
pub async fn outer_size(&self) -> crate::Result<PhysicalSize> {
Ok(PhysicalSize(
self.0
.outerSize()
.await
.map_err(Error::Other)?
.unchecked_into(),
))
Ok(PhysicalSize(self.0.outerSize().await?.unchecked_into()))
}
pub async fn is_fullscreen(&self) -> crate::Result<bool> {
let js_val = self.0.isFullscreen().await.map_err(Error::Other)?;
let js_val = self.0.isFullscreen().await?;
Ok(serde_wasm_bindgen::from_value(js_val)?)
}
pub async fn is_maximized(&self) -> crate::Result<bool> {
let js_val = self.0.isMaximized().await.map_err(Error::Other)?;
let js_val = self.0.isMaximized().await?;
Ok(serde_wasm_bindgen::from_value(js_val)?)
}
pub async fn is_decorated(&self) -> crate::Result<bool> {
let js_val = self.0.isDecorated().await.map_err(Error::Other)?;
let js_val = self.0.isDecorated().await?;
Ok(serde_wasm_bindgen::from_value(js_val)?)
}
pub async fn is_resizable(&self) -> crate::Result<bool> {
let js_val = self.0.isResizable().await.map_err(Error::Other)?;
let js_val = self.0.isResizable().await?;
Ok(serde_wasm_bindgen::from_value(js_val)?)
}
pub async fn is_visible(&self) -> crate::Result<bool> {
let js_val = self.0.isVisible().await.map_err(Error::Other)?;
let js_val = self.0.isVisible().await?;
Ok(serde_wasm_bindgen::from_value(js_val)?)
}
pub async fn theme(&self) -> crate::Result<Theme> {
let js_val = self.0.theme().await.map_err(Error::Other)?;
let js_val = self.0.theme().await?;
let str = serde_wasm_bindgen::from_value::<String>(js_val)?;
@ -224,186 +204,154 @@ impl WebviewWindow {
}
pub async fn center(&self) -> crate::Result<()> {
self.0.center().await.map_err(Error::Other)
Ok(self.0.center().await?)
}
pub async fn request_user_attention(
&self,
request_type: UserAttentionType,
) -> crate::Result<()> {
self.0
.requestUserAttention(request_type as u32)
.await
.map_err(Error::Other)
Ok(self.0.requestUserAttention(request_type as u32).await?)
}
pub async fn set_resizable(&self, resizable: bool) -> crate::Result<()> {
self.0.setResizable(resizable).await.map_err(Error::Other)
Ok(self.0.setResizable(resizable).await?)
}
pub async fn set_title(&self, title: impl AsRef<str>) -> crate::Result<()> {
self.0.setTitle(title.as_ref()).await.map_err(Error::Other)
Ok(self.0.setTitle(title.as_ref()).await?)
}
pub async fn maximize(&self) -> crate::Result<()> {
self.0.maximize().await.map_err(Error::Other)
Ok(self.0.maximize().await?)
}
pub async fn unmaximize(&self) -> crate::Result<()> {
self.0.unmaximize().await.map_err(Error::Other)
Ok(self.0.unmaximize().await?)
}
pub async fn toggle_maximize(&self) -> crate::Result<()> {
self.0.toggleMaximize().await.map_err(Error::Other)
Ok(self.0.toggleMaximize().await?)
}
pub async fn minimize(&self) -> crate::Result<()> {
self.0.minimize().await.map_err(Error::Other)
Ok(self.0.minimize().await?)
}
pub async fn unminimize(&self) -> crate::Result<()> {
self.0.unminimize().await.map_err(Error::Other)
Ok(self.0.unminimize().await?)
}
pub async fn show(&self) -> crate::Result<()> {
self.0.show().await.map_err(Error::Other)
Ok(self.0.show().await?)
}
pub async fn hide(&self) -> crate::Result<()> {
self.0.hide().await.map_err(Error::Other)
Ok(self.0.hide().await?)
}
pub async fn close(&self) -> crate::Result<()> {
self.0.close().await.map_err(Error::Other)
Ok(self.0.close().await?)
}
pub async fn set_decorations(&self, decorations: bool) -> crate::Result<()> {
self.0
.setDecorations(decorations)
.await
.map_err(Error::Other)
Ok(self.0.setDecorations(decorations).await?)
}
pub async fn set_always_on_top(&self, always_on_top: bool) -> crate::Result<()> {
self.0
.setAlwaysOnTop(always_on_top)
.await
.map_err(Error::Other)
Ok(self.0.setAlwaysOnTop(always_on_top).await?)
}
pub async fn set_size(&self, size: Size) -> crate::Result<()> {
match size {
Size::Physical(size) => self.0.setSizePhysical(size.0).await.map_err(Error::Other),
Size::Logical(size) => self.0.setSizeLogical(size.0).await.map_err(Error::Other),
Size::Physical(size) => self.0.setSizePhysical(size.0).await?,
Size::Logical(size) => self.0.setSizeLogical(size.0).await?,
}
Ok(())
}
pub async fn set_min_size(&self, size: Option<Size>) -> crate::Result<()> {
match size {
None => self.0.setMinSizePhysical(None).await.map_err(Error::Other),
Some(Size::Physical(size)) => self
.0
.setMinSizePhysical(Some(size.0))
.await
.map_err(Error::Other),
Some(Size::Logical(size)) => self
.0
.setMinSizeLogical(Some(size.0))
.await
.map_err(Error::Other),
None => self.0.setMinSizePhysical(None).await?,
Some(Size::Physical(size)) => self.0.setMinSizePhysical(Some(size.0)).await?,
Some(Size::Logical(size)) => self.0.setMinSizeLogical(Some(size.0)).await?,
}
Ok(())
}
pub async fn set_max_size(&self, size: Option<Size>) -> crate::Result<()> {
match size {
None => self.0.setMaxSizePhysical(None).await.map_err(Error::Other),
Some(Size::Physical(size)) => self
.0
.setMaxSizePhysical(Some(size.0))
.await
.map_err(Error::Other),
Some(Size::Logical(size)) => self
.0
.setMaxSizeLogical(Some(size.0))
.await
.map_err(Error::Other),
None => self.0.setMaxSizePhysical(None).await?,
Some(Size::Physical(size)) => self.0.setMaxSizePhysical(Some(size.0)).await?,
Some(Size::Logical(size)) => self.0.setMaxSizeLogical(Some(size.0)).await?,
}
Ok(())
}
pub async fn set_position(&self, position: Position) -> crate::Result<()> {
match position {
Position::Physical(pos) => self
.0
.setPositionPhysical(pos.0)
.await
.map_err(Error::Other),
Position::Logical(pos) => self.0.setPositionLogical(pos.0).await.map_err(Error::Other),
Position::Physical(pos) => self.0.setPositionPhysical(pos.0).await?,
Position::Logical(pos) => self.0.setPositionLogical(pos.0).await?,
}
Ok(())
}
pub async fn set_fullscreen(&self, fullscreen: bool) -> crate::Result<()> {
self.0.setFullscreen(fullscreen).await.map_err(Error::Other)
Ok(self.0.setFullscreen(fullscreen).await?)
}
pub async fn set_focus(&self) -> crate::Result<()> {
self.0.setFocus().await.map_err(Error::Other)
Ok(self.0.setFocus().await?)
}
pub async fn set_icon(&self, icon: &[u8]) -> crate::Result<()> {
self.0.setIcon(icon).await.map_err(Error::Other)
Ok(self.0.setIcon(icon).await?)
}
pub async fn set_skip_taskbar(&self, skip: bool) -> crate::Result<()> {
self.0.setSkipTaskbar(skip).await.map_err(Error::Other)
Ok(self.0.setSkipTaskbar(skip).await?)
}
pub async fn set_cursor_grab(&self, grab: bool) -> crate::Result<()> {
self.0.setCursorGrab(grab).await.map_err(Error::Other)
Ok(self.0.setCursorGrab(grab).await?)
}
pub async fn set_cursor_visible(&self, visible: bool) -> crate::Result<()> {
self.0.setCursorVisible(visible).await.map_err(Error::Other)
Ok(self.0.setCursorVisible(visible).await?)
}
pub async fn set_cursor_icon(&self, icon: CursorIcon) -> crate::Result<()> {
self.0
.setCursorIcon(&icon.to_string())
.await
.map_err(Error::Other)
Ok(self.0.setCursorIcon(&icon.to_string()).await?)
}
pub async fn set_cursor_position(&self, position: Position) -> crate::Result<()> {
match position {
Position::Physical(pos) => self
.0
.setCursorPositionPhysical(pos.0)
.await
.map_err(Error::Other),
Position::Logical(pos) => self
.0
.setCursorPositionLogical(pos.0)
.await
.map_err(Error::Other),
Position::Physical(pos) => self.0.setCursorPositionPhysical(pos.0).await?,
Position::Logical(pos) => self.0.setCursorPositionLogical(pos.0).await?
}
Ok(())
}
pub async fn set_ignore_cursor_events(&self, ignore: bool) -> crate::Result<()> {
self.0
.setIgnoreCursorEvents(ignore)
.await
.map_err(Error::Other)
Ok(self.0.setIgnoreCursorEvents(ignore).await?)
}
pub async fn start_dragging(&self) -> crate::Result<()> {
self.0.startDragging().await.map_err(Error::Other)
Ok(self.0.startDragging().await?)
}
#[inline(always)]
pub async fn emit<T: Serialize>(&self, event: &str, payload: &T) -> crate::Result<()> {
self.0
.emit(event, serde_wasm_bindgen::to_value(payload).unwrap())
.await
.map_err(Error::Other)
.await?;
Ok(())
}
#[inline(always)]
@ -416,7 +364,7 @@ impl WebviewWindow {
(handler)(serde_wasm_bindgen::from_value(raw).unwrap())
});
let unlisten = self.0.listen(event, &closure).await.map_err(Error::Other)?;
let unlisten = self.0.listen(event, &closure).await?;
closure.forget();
@ -436,7 +384,7 @@ impl WebviewWindow {
(handler)(serde_wasm_bindgen::from_value(raw).unwrap())
});
let unlisten = self.0.once(event, &closure).await.map_err(Error::Other)?;
let unlisten = self.0.once(event, &closure).await?;
closure.forget();