use proc_macro2::Span;
use thiserror::Error as ThisError;
#[derive(Debug)]
pub struct Error {
pub span: Span,
pub kind: ErrorKind,
}
impl Error {
pub fn new(span: Span, kind: ErrorKind) -> Self {
Self { span, kind }
}
pub fn from_darling(error: darling::Error, span: Span) -> Self {
Self {
span,
kind: ErrorKind::UnparsableAttribute(error.to_string()),
}
}
}
#[derive(Debug, ThisError)]
pub enum ErrorKind {
#[error("{0}")]
UnparsableAttribute(String),
#[error("Factory can only be derived from named structs, enum given")]
UnsupportedDataStructureEnum,
#[error("Factory can only be derived from named structs, tuple struct given")]
UnsupportedDataStructureTupleStruct,
#[error("Factory can only be derived from named structs, union given")]
UnsupportedDataStructureUnion,
#[error("Factory can only be derived from named structs, unit struct given")]
UnsupportedDataStructureUnitStruct,
#[error("Missing primary key, either add an id column or mark an existing column as primary")]
MissingPrimaryKey,
#[error("Invalid faker expression: {0}")]
InvalidFakerExpression(String),
#[error("`alias` can only be used on `belongs_to` or `HasMany` fields")]
AliasWithoutRelation,
#[error("Duplicate alias `{0}`: each alias name must be unique within a model")]
DuplicateAlias(String),
}
impl From<Error> for syn::Error {
fn from(error: Error) -> Self {
syn::Error::new(error.span, error.kind.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_crate_error_converts_to_syn_error() {
let error = Error::new(Span::call_site(), ErrorKind::MissingPrimaryKey);
let error: syn::Error = error.into();
assert_eq!(
error.to_string(),
"Missing primary key, either add an id column or mark an existing column as primary"
);
}
}