rqjs_ext/utils/
result.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3use std::result::Result as StdResult;
4
5use rquickjs::{Ctx, Exception, Result};
6
7pub trait ResultExt<T> {
8    fn or_throw_msg(self, ctx: &Ctx, msg: &str) -> Result<T>;
9    fn or_throw(self, ctx: &Ctx) -> Result<T>;
10}
11
12pub trait OptionExt<T> {
13    fn and_then_ok<U, E, F>(self, f: F) -> StdResult<Option<U>, E>
14    where
15        F: FnOnce(T) -> StdResult<Option<U>, E>;
16}
17
18impl<T, E: std::fmt::Display> ResultExt<T> for StdResult<T, E> {
19    fn or_throw_msg(self, ctx: &Ctx, msg: &str) -> Result<T> {
20        self.map_err(|e| Exception::throw_message(ctx, &format!("{}. {}", msg, &e.to_string())))
21    }
22
23    fn or_throw(self, ctx: &Ctx) -> Result<T> {
24        self.map_err(|err| Exception::throw_message(ctx, &err.to_string()))
25    }
26}
27
28impl<T> ResultExt<T> for Option<T> {
29    fn or_throw_msg(self, ctx: &Ctx, msg: &str) -> Result<T> {
30        self.ok_or(Exception::throw_message(ctx, msg))
31    }
32
33    fn or_throw(self, ctx: &Ctx) -> Result<T> {
34        self.ok_or(Exception::throw_message(ctx, "Value is not present"))
35    }
36}
37
38impl<T> OptionExt<T> for Option<T> {
39    fn and_then_ok<U, E, F>(self, f: F) -> StdResult<Option<U>, E>
40    where
41        F: FnOnce(T) -> StdResult<Option<U>, E>,
42    {
43        match self {
44            Some(v) => f(v),
45            None => Ok(None),
46        }
47    }
48}