Skip to main content

sea_orm_sluggable/
error.rs

1use std::fmt;
2
3use sea_orm::DbErr;
4
5/// Why a slug could not be generated.
6#[derive(Debug)]
7#[non_exhaustive]
8pub enum SlugError {
9    /// The text had no letters or digits left after transliteration, e.g. "!!!".
10    Empty,
11    /// The uniqueness check failed in the database.
12    Db(DbErr),
13}
14
15impl fmt::Display for SlugError {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        match self {
18            Self::Empty => write!(f, "the text produces an empty slug"),
19            Self::Db(err) => write!(f, "slug uniqueness check failed: {err}"),
20        }
21    }
22}
23
24impl std::error::Error for SlugError {
25    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
26        match self {
27            Self::Empty => None,
28            Self::Db(err) => Some(err),
29        }
30    }
31}
32
33impl From<DbErr> for SlugError {
34    fn from(err: DbErr) -> Self {
35        Self::Db(err)
36    }
37}
38
39/// Lets `before_save` use `?` on [`fill_slug`](crate::fill_slug): `SeaORM` hooks
40/// must return `DbErr`.
41impl From<SlugError> for DbErr {
42    fn from(err: SlugError) -> Self {
43        match err {
44            SlugError::Db(err) => err,
45            SlugError::Empty => Self::Custom(err.to_string()),
46        }
47    }
48}