utopia_balancer/error.rs
1//! The error type of the balancer.
2
3/// Why choosing an option failed.
4///
5/// PHP: one variant per PHP exception class (see [`Error::php_class`]).
6#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
7pub enum Error {
8 /// An algorithm was asked to choose from no options at all.
9 ///
10 /// PHP: `\ValueError`, which `array_rand()` throws when
11 /// `Algorithm\Random::run()` gets an empty array.
12 #[error("{0}")]
13 Value(String),
14 /// A [`RoundRobin`](crate::RoundRobin) index that cannot move past
15 /// `i64::MAX`.
16 ///
17 /// PHP: `\TypeError`, which incrementing the typed `int $index` property
18 /// past `PHP_INT_MAX` throws.
19 #[error("{0}")]
20 Type(String),
21 /// An error raised by a custom [`Algorithm`](crate::Algorithm), with the
22 /// PHP class it stands for.
23 #[error("{message}")]
24 Custom {
25 /// The PHP exception class.
26 class: &'static str,
27 /// The message.
28 message: String,
29 },
30}
31
32impl Error {
33 /// The name of the exception class this error matches, such as
34 /// `ValueError`.
35 ///
36 /// PHP: the class of the exception `utopia-php/balancer` throws in the
37 /// same case.
38 pub fn php_class(&self) -> &'static str {
39 match self {
40 Error::Value(_) => "ValueError",
41 Error::Type(_) => "TypeError",
42 Error::Custom { class, .. } => class,
43 }
44 }
45}