use formatparse_core::error::FormatParseError;
use pyo3::prelude::*;
pub fn core_error_to_py_err(err: FormatParseError) -> PyErr {
match err {
FormatParseError::PatternError(msg) => {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Pattern error: {}", msg))
}
FormatParseError::RegexError(msg) => errors::regex_error(msg.as_str()),
FormatParseError::ConversionError(value, target_type) => {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Invalid {}: {}",
target_type, value
))
}
FormatParseError::RepeatedNameError(name) => {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Repeated name '{}' with mismatched types",
name
))
}
FormatParseError::CustomTypeError(type_name, msg) => {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Custom type '{}' error: {}",
type_name, msg
))
}
FormatParseError::RegexGroupIndexError(type_name, actual, expected) => {
PyErr::new::<pyo3::exceptions::PyIndexError, _>(format!(
"Custom type '{}' pattern has {} capturing groups but regex_group_count is {}",
type_name, actual, expected
))
}
FormatParseError::NotImplementedError(feature) => {
PyErr::new::<pyo3::exceptions::PyNotImplementedError, _>(format!(
"{} is not supported",
feature
))
}
FormatParseError::MissingFieldError(field) => {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Missing required field: {}",
field
))
}
}
}
pub fn fancy_regex_match_error(e: fancy_regex::Error) -> PyErr {
PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Regex match error: {}", e))
}
pyo3::create_exception!(
_formatparse,
PatternParseMismatch,
pyo3::exceptions::PyValueError
);
pub mod errors {
use super::*;
pub fn regex_error(msg: &str) -> PyErr {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Invalid regex pattern: {}", msg))
}
pub fn conversion_error(value: &str, target_type: &str) -> PyErr {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Invalid {}: {}",
target_type, value
))
}
pub fn repeated_name_error(name: &str) -> PyErr {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Repeated name '{}' with mismatched types",
name
))
}
pub fn custom_type_error(type_name: &str, msg: &str) -> PyErr {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Custom type '{}' error: {}",
type_name, msg
))
}
pub fn regex_group_index_error(type_name: &str, actual: usize, expected: i64) -> PyErr {
PyErr::new::<pyo3::exceptions::PyIndexError, _>(format!(
"Custom type '{}' pattern has {} capturing groups but regex_group_count is {}",
type_name, actual, expected
))
}
pub fn missing_field_error(field: &str) -> PyErr {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Missing required field: {}",
field
))
}
}
pub use errors::*;