proxy_wasm_experimental/
error.rs

1// Copyright 2020 Tetrate
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt;
16
17use crate::types::Status;
18
19/// A boxed [`Error`].
20///
21/// [`Error`]: https://doc.rust-lang.org/std/fmt/struct.Error.html
22pub type Error = Box<dyn std::error::Error + Send + Sync>;
23
24/// A specialized [`Result`] type.
25///
26/// [`Result`]: https://doc.rust-lang.org/core/result/enum.Result.html
27pub type Result<T> = core::result::Result<T, Error>;
28
29/// An error to call a Host ABI function.
30#[derive(Debug)]
31pub struct HostCallError<'a> {
32    function: &'a str,
33    status: Status,
34}
35
36impl<'a> HostCallError<'a> {
37    pub(crate) fn new(function: &'a str, status: Status) -> Self {
38        HostCallError { function, status }
39    }
40
41    pub fn module(&self) -> &'a str {
42        "env"
43    }
44
45    pub fn function(&self) -> &'a str {
46        self.function
47    }
48
49    pub fn status(&self) -> Status {
50        self.status
51    }
52}
53
54impl<'a> fmt::Display for HostCallError<'a> {
55    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56        write!(
57            f,
58            "call to the host ABI function \"{}.{}\" has failed with status code {}",
59            self.module(),
60            self.function,
61            self.status as u32,
62        )
63    }
64}
65
66impl<'a> std::error::Error for HostCallError<'a> {}
67
68/// An error to parse the response from a Host ABI.
69#[derive(Debug)]
70pub struct HostResponseError<'a> {
71    function: &'a str,
72    error: Error,
73}
74
75impl<'a> HostResponseError<'a> {
76    pub(crate) fn new(function: &'a str, error: Error) -> Self {
77        HostResponseError { function, error }
78    }
79
80    pub fn module(&self) -> &'a str {
81        "env"
82    }
83
84    pub fn function(&self) -> &'a str {
85        self.function
86    }
87}
88
89impl<'a> fmt::Display for HostResponseError<'a> {
90    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
91        write!(
92            f,
93            "failed to parse response from the host ABI function \"{}.{}\": {}",
94            self.module(),
95            self.function,
96            self.error,
97        )
98    }
99}
100
101impl<'a> std::error::Error for HostResponseError<'a> {
102    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
103        Some(&*self.error)
104    }
105}