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
//! Represents the [`IonSchemaResult`] type for error handling.
//!
//! [`IonSchemaResult<T, E>`][`IonSchemaResult`]  is the type used for returning and propagating errors.
//! It is an enum with the variants, Ok(T), representing success and containing a value,and Err(E), representing an [`IonSchemaError`].

use crate::violation::Violation;
use ion_rs::result::IonError;
use std::io;
use thiserror::Error;

/// A unified Result type representing the outcome of method calls that may fail.
pub type IonSchemaResult<T> = Result<T, IonSchemaError>;

/// A Result type representing the outcome of validation that may result in violations.
pub type ValidationResult = Result<(), Violation>;

/// Represents the different types of high-level failures that might occur when reading Ion Schema.
#[derive(Debug, Error)]
pub enum IonSchemaError {
    /// Indicates that an io error occurred while loading a schema
    #[error("{source:?}")]
    IoError {
        #[from]
        source: io::Error,
    },

    /// Indicates failure for schema which has unresolvable imports/types
    #[error("{description}")]
    UnresolvableSchemaError { description: String },

    /// Indicates failure due to invalid schema syntax
    #[error("{description}")]
    InvalidSchemaError { description: String },

    /// Indicates failure due to ion-rust error defined by IonError
    #[error("{source:?}")]
    IonError {
        #[from]
        source: IonError,
    },
}

/// A convenience method for creating an IonSchemaResult containing an IonSchemaError::UnresolvableSchemaError
/// with the provided description text.
pub fn unresolvable_schema_error<T, S: AsRef<str>>(description: S) -> IonSchemaResult<T> {
    Err(IonSchemaError::UnresolvableSchemaError {
        description: description.as_ref().to_string(),
    })
}

/// A convenience method for creating an  IonSchemaError::InvalidSchemaError with the provided operation
/// text.
pub fn invalid_schema_error_raw<S: AsRef<str>>(description: S) -> IonSchemaError {
    IonSchemaError::InvalidSchemaError {
        description: description.as_ref().to_string(),
    }
}

/// A convenience method for creating an IonSchemaResult containing an IonSchemaError::InvalidSchemaError
/// with the provided description text.
pub fn invalid_schema_error<T, S: AsRef<str>>(description: S) -> IonSchemaResult<T> {
    Err(IonSchemaError::InvalidSchemaError {
        description: description.as_ref().to_string(),
    })
}

/// A convenience method for creating an  IonSchemaError::InvalidSchemaError with the provided operation
/// text.
pub fn unresolvable_schema_error_raw<S: AsRef<str>>(description: S) -> IonSchemaError {
    IonSchemaError::UnresolvableSchemaError {
        description: description.as_ref().to_string(),
    }
}