fidl_codec/
error.rs

1// Copyright 2019 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use nom::error::{ErrorKind, ParseError};
6use serde_json::error::Error as SerdeError;
7use std::result;
8use std::str::Utf8Error;
9use thiserror::Error;
10
11/// A result for codec operations.
12pub type Result<T> = result::Result<T, Error>;
13
14/// Error type used by the codec.
15#[derive(Debug, Error)]
16pub enum Error {
17    #[error("Error loading from FIDL JSON: {0}")]
18    LibraryError(String),
19    #[error("Could not parse FIDL JSON: {0}")]
20    LibraryParseError(SerdeError),
21    #[error("Encoding Error: {0}")]
22    EncodeError(String),
23    #[error("Decoding Error: {0}")]
24    DecodeError(String),
25    #[error("Value Error: {0}")]
26    ValueError(String),
27    #[error("UTF-8 Decoding error: {0}")]
28    Utf8Error(Utf8Error),
29    #[error("RecursionLimitExceeded")]
30    RecursionLimitExceeded,
31}
32
33impl From<SerdeError> for Error {
34    fn from(error: SerdeError) -> Self {
35        Error::LibraryParseError(error)
36    }
37}
38
39impl From<Error> for nom::Err<Error> {
40    fn from(error: Error) -> Self {
41        nom::Err::Failure(error)
42    }
43}
44
45impl From<nom::Err<Error>> for Error {
46    fn from(error: nom::Err<Error>) -> Self {
47        match error {
48            nom::Err::Incomplete(_) => Error::DecodeError("<Parsing Incomplete>".to_owned()),
49            nom::Err::Error(x) | nom::Err::Failure(x) => x.into(),
50        }
51    }
52}
53
54impl ParseError<&[u8]> for Error {
55    fn from_error_kind(_: &[u8], kind: ErrorKind) -> Self {
56        Error::DecodeError(format!("Nom encountered an error (kind: {})", kind.description()))
57    }
58
59    fn append(_: &[u8], kind: ErrorKind, other: Self) -> Self {
60        Error::DecodeError(format!(
61            "Nom encountered an error (kind: {}) caused by: {}",
62            kind.description(),
63            other
64        ))
65    }
66}