elm_rust_binding/
error.rs

1use std::{fmt::Display, path::PathBuf};
2
3/// Main error type for this crate.
4#[derive(Debug)]
5pub enum Error {
6    /// JavaScript parsing or execution error.
7    RuntimeError(rustyscript::Error),
8    // Could not infer elm types based on given rust input/output types.
9    TypeAnalysisError(serde_reflection::Error),
10    // Failed to read/write/delete files.
11    DiskIOError {
12        path: PathBuf,
13        source: std::io::Error,
14    },
15    // The qualified function name had the wrong format, or the Elm code did not compile.
16    InvalidElmCall(String),
17}
18
19/// A simple Result alias with the crate specific `Error` type.
20pub type Result<T> = std::result::Result<T, Error>;
21
22impl Error {
23    pub(crate) fn map_disk_error(path: PathBuf) -> impl FnOnce(std::io::Error) -> Error {
24        |source| Error::DiskIOError { path, source }
25    }
26}
27
28impl Display for Error {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        match self {
31            Error::RuntimeError(error) => error.fmt(f),
32            Error::TypeAnalysisError(error) => error.fmt(f),
33            Error::DiskIOError { path, source } => {
34                f.write_fmt(format_args!("DiskIOError at {path:?}: {source}"))
35            }
36            Error::InvalidElmCall(function_name) => f.write_fmt(format_args!("Invalid Elm Call {function_name}. Expected format is MyModule.MySubmodule.myMethod."))
37        }
38    }
39}
40
41impl std::error::Error for Error {}
42
43impl From<rustyscript::Error> for Error {
44    fn from(value: rustyscript::Error) -> Self {
45        Error::RuntimeError(value)
46    }
47}
48
49impl From<serde_reflection::Error> for Error {
50    fn from(value: serde_reflection::Error) -> Self {
51        Error::TypeAnalysisError(value)
52    }
53}