From fb1832feb868a81e2d10a1707c57df4623304313 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81rni=20Dagur?= Date: Sat, 26 Jun 2021 16:20:29 +0000 Subject: Create a custom exception type for this library --- src/lib.rs | 40 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index 54031dd..172f025 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -17,7 +17,8 @@ use adblock::engine::Engine as RustEngine; use adblock::lists::FilterFormat; use adblock::lists::FilterSet as RustFilterSet; use pyo3::class::PyObjectProtocol; -use pyo3::exceptions::PyValueError; +use pyo3::create_exception; +use pyo3::exceptions::PyException; use pyo3::prelude::*; use pyo3::types::PyBytes; use pyo3::PyErr; @@ -31,12 +32,28 @@ use std::io::{Read, Write}; /// Brave's adblocking library in Python! #[pymodule] -fn adblock(_py: Python<'_>, m: &PyModule) -> PyResult<()> { +fn adblock(py: Python<'_>, m: &PyModule) -> PyResult<()> { m.add("__version__", env!("CARGO_PKG_VERSION"))?; m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add("AdblockException", py.get_type::())?; + m.add("BlockerException", py.get_type::())?; + m.add("SerializationError", py.get_type::())?; + m.add( + "DeserializationError", + py.get_type::(), + )?; + m.add( + "OptimizedFilterExistence", + py.get_type::(), + )?; + m.add( + "BadFilterAddUnsupported", + py.get_type::(), + )?; + m.add("FilterExists", py.get_type::())?; Ok(()) } @@ -141,9 +158,24 @@ impl Display for BlockerError { } } +create_exception!(adblock, AdblockException, PyException); +create_exception!(adblock, BlockerException, AdblockException); +create_exception!(adblock, SerializationError, BlockerException); +create_exception!(adblock, DeserializationError, BlockerException); +create_exception!(adblock, OptimizedFilterExistence, BlockerException); +create_exception!(adblock, BadFilterAddUnsupported, BlockerException); +create_exception!(adblock, FilterExists, BlockerException); + impl Into for BlockerError { fn into(self) -> PyErr { - PyErr::new::(format!("{:?}", self)) + let msg = format!("{:?}", self); + match self { + Self::SerializationError => PyErr::new::(msg), + Self::DeserializationError => PyErr::new::(msg), + Self::OptimizedFilterExistence => PyErr::new::(msg), + Self::BadFilterAddUnsupported => PyErr::new::(msg), + Self::FilterExists => PyErr::new::(msg), + } } } @@ -163,7 +195,7 @@ fn filter_format_from_string(filter_format: &str) -> PyResult { match filter_format { "standard" => Ok(FilterFormat::Standard), "hosts" => Ok(FilterFormat::Hosts), - _ => Err(PyErr::new::("Invalid format value")), + _ => Err(PyErr::new::("Invalid format value")), } } -- cgit v1.2.3