scale_encode/error/mod.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
// Copyright (C) 2023 Parity Technologies (UK) Ltd. (admin@parity.io)
// This file is a part of the scale-encode crate.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! An error that is emitted whenever some encoding fails.
mod context;
use alloc::{borrow::Cow, boxed::Box, string::String};
use core::fmt::Display;
pub use context::{Context, Location};
/// An error produced while attempting to encode some type.
#[derive(Debug)]
pub struct Error {
context: Context,
kind: ErrorKind,
}
#[cfg(feature = "std")]
impl std::error::Error for Error {}
impl Error {
/// Construct a new error given an error kind.
pub fn new(kind: ErrorKind) -> Error {
Error {
context: Context::new(),
kind,
}
}
/// Construct a new, custom error.
pub fn custom(error: impl CustomError) -> Error {
Error::new(ErrorKind::Custom(Box::new(error)))
}
/// Construct a custom error from a static string.
pub fn custom_str(error: &'static str) -> Error {
#[derive(derive_more::Display, Debug)]
pub struct StrError(pub &'static str);
#[cfg(feature = "std")]
impl std::error::Error for StrError {}
Error::new(ErrorKind::Custom(Box::new(StrError(error))))
}
/// Construct a custom error from an owned string.
pub fn custom_string(error: String) -> Error {
#[derive(derive_more::Display, Debug)]
pub struct StringError(String);
#[cfg(feature = "std")]
impl std::error::Error for StringError {}
Error::new(ErrorKind::Custom(Box::new(StringError(error))))
}
/// Retrieve more information about what went wrong.
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
/// Retrieve details about where the error occurred.
pub fn context(&self) -> &Context {
&self.context
}
/// Give some context to the error.
pub fn at(mut self, loc: Location) -> Self {
self.context.push(loc);
Error {
context: self.context,
kind: self.kind,
}
}
/// Note which sequence index the error occurred in.
pub fn at_idx(mut self, idx: usize) -> Self {
self.context.push(Location::idx(idx));
Error {
context: self.context,
kind: self.kind,
}
}
/// Note which field the error occurred in.
pub fn at_field(mut self, field: impl Into<Cow<'static, str>>) -> Self {
self.context.push(Location::field(field));
Error {
context: self.context,
kind: self.kind,
}
}
/// Note which variant the error occurred in.
pub fn at_variant(mut self, variant: impl Into<Cow<'static, str>>) -> Self {
self.context.push(Location::variant(variant));
Error {
context: self.context,
kind: self.kind,
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let path = self.context.path();
let kind = &self.kind;
write!(f, "Error at {path}: {kind}")
}
}
/// The underlying nature of the error.
#[derive(Debug, derive_more::From, derive_more::Display)]
pub enum ErrorKind {
/// There was an error resolving the type via the given [`crate::TypeResolver`].
#[display("Failed to resolve type: {_0}")]
TypeResolvingError(String),
/// Cannot find a given type.
#[display("Cannot find type with identifier {_0}")]
TypeNotFound(String),
/// Cannot encode the actual type given into the target type ID.
#[display("Cannot encode {actual:?} into type with ID {expected_id}")]
WrongShape {
/// The actual kind we have to encode
actual: Kind,
/// Identifier for the expected type
expected_id: String,
},
/// The types line up, but the expected length of the target type is different from the length of the input value.
#[display("Cannot encode to type; expected length {expected_len} but got length {actual_len}")]
WrongLength {
/// Length we have
actual_len: usize,
/// Length expected for type.
expected_len: usize,
},
/// We cannot encode the number given into the target type; it's out of range.
#[display("Number {value} is out of range for target type with identifier {expected_id}")]
NumberOutOfRange {
/// A string represenatation of the numeric value that was out of range.
value: String,
/// Identifier for the expected numeric type that we tried to encode it to.
expected_id: String,
},
/// Cannot find a variant with a matching name on the target type.
#[display("Variant {name} does not exist on type with identifier {expected_id}")]
CannotFindVariant {
/// Variant name we can't find in the expected type.
name: String,
/// Identifier for the expected type.
expected_id: String,
},
/// Cannot find a field on our source type that's needed for the target type.
#[display("Field {name} does not exist in our source struct")]
CannotFindField {
/// Name of the field which was not provided.
name: String,
},
/// A custom error.
#[from]
#[display("Custom error: {_0}")]
Custom(Box<dyn CustomError>),
}
/// Anything implementing this trait can be used in [`ErrorKind::Custom`].
#[cfg(feature = "std")]
pub trait CustomError: std::error::Error + Send + Sync + 'static {}
#[cfg(feature = "std")]
impl<T: std::error::Error + Send + Sync + 'static> CustomError for T {}
/// Anything implementing this trait can be used in [`ErrorKind::Custom`].
#[cfg(not(feature = "std"))]
pub trait CustomError: core::fmt::Debug + core::fmt::Display + Send + Sync + 'static {}
#[cfg(not(feature = "std"))]
impl<T: core::fmt::Debug + core::fmt::Display + Send + Sync + 'static> CustomError for T {}
/// The kind of type that we're trying to encode.
#[allow(missing_docs)]
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Kind {
Struct,
Tuple,
Variant,
Array,
BitSequence,
Bool,
Char,
Str,
Number,
}
#[cfg(test)]
mod test {
use super::*;
#[derive(Debug, derive_more::Display)]
enum MyError {
Foo,
}
#[cfg(feature = "std")]
impl std::error::Error for MyError {}
#[test]
fn custom_error() {
// Just a compile-time check that we can ergonomically provide an arbitrary custom error:
Error::custom(MyError::Foo);
}
}