22
33use std:: { ops:: Deref , sync:: Arc } ;
44
5- use anyhow:: anyhow;
65use jsonschema:: { options, Draft , Validator } ;
76use serde_json:: Value ;
87
@@ -14,6 +13,19 @@ use serde_json::Value;
1413#[ derive( Clone ) ]
1514pub struct JsonSchema ( Arc < Validator > ) ;
1615
16+ /// `JsonSchema` building error type.
17+ #[ derive( Debug , thiserror:: Error ) ]
18+ pub enum SchemaBuildError {
19+ /// Invalid JSON Schema error.
20+ #[ error( "Invalid JSON Schema" ) ]
21+ InvalidSchema ,
22+ /// Undetectable JSON schema version.
23+ #[ error(
24+ "Could not detect draft version and schema is not valid against Draft2020-12 or Draft7"
25+ ) ]
26+ UndetectableDraft ,
27+ }
28+
1729impl Deref for JsonSchema {
1830 type Target = Validator ;
1931
@@ -23,7 +35,7 @@ impl Deref for JsonSchema {
2335}
2436
2537impl TryFrom < & Value > for JsonSchema {
26- type Error = anyhow :: Error ;
38+ type Error = SchemaBuildError ;
2739
2840 fn try_from ( schema : & Value ) -> std:: result:: Result < Self , Self :: Error > {
2941 let draft_version = if let Some ( schema) = schema. get ( "$schema" ) . and_then ( |s| s. as_str ( ) ) {
@@ -42,7 +54,7 @@ impl TryFrom<&Value> for JsonSchema {
4254 let validator = options ( )
4355 . with_draft ( draft)
4456 . build ( schema)
45- . map_err ( |e| anyhow ! ( "Invalid JSON Schema: {e}" ) ) ?;
57+ . map_err ( |_| SchemaBuildError :: InvalidSchema ) ?;
4658
4759 Ok ( JsonSchema ( validator. into ( ) ) )
4860 } else {
@@ -57,9 +69,7 @@ impl TryFrom<&Value> for JsonSchema {
5769 return Ok ( JsonSchema ( validator. into ( ) ) ) ;
5870 }
5971
60- Err ( anyhow ! (
61- "Could not detect draft version and schema is not valid against Draft2020-12 or Draft7"
62- ) )
72+ Err ( SchemaBuildError :: UndetectableDraft )
6373 }
6474 }
6575}
0 commit comments