1use std::fmt;
61use thiserror::Error;
62
63pub type QueryResult<T> = Result<T, QueryError>;
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
68pub enum ErrorCode {
69 RecordNotFound = 1001,
72 NotUnique = 1002,
74 InvalidFilter = 1003,
76 InvalidSelect = 1004,
78 RequiredFieldMissing = 1005,
80
81 UniqueConstraint = 2001,
84 ForeignKeyConstraint = 2002,
86 CheckConstraint = 2003,
88 NotNullConstraint = 2004,
90
91 ConnectionFailed = 3001,
94 PoolExhausted = 3002,
96 ConnectionTimeout = 3003,
98 AuthenticationFailed = 3004,
100 SslError = 3005,
102
103 TransactionFailed = 4001,
106 Deadlock = 4002,
108 SerializationFailure = 4003,
110 TransactionClosed = 4004,
112
113 QueryTimeout = 5001,
116 SqlSyntax = 5002,
118 InvalidParameter = 5003,
120 QueryTooComplex = 5004,
122 DatabaseError = 5005,
124
125 InvalidDataType = 6001,
128 SerializationError = 6002,
130 DeserializationError = 6003,
132 DataTruncation = 6004,
134
135 InvalidConfiguration = 7001,
138 MissingConfiguration = 7002,
140 InvalidConnectionString = 7003,
142
143 Internal = 9001,
146 Unknown = 9999,
148}
149
150impl ErrorCode {
151 pub fn code(&self) -> String {
153 format!("P{}", *self as u16)
154 }
155
156 pub fn description(&self) -> &'static str {
158 match self {
159 Self::RecordNotFound => "Record not found",
160 Self::NotUnique => "Multiple records found",
161 Self::InvalidFilter => "Invalid filter condition",
162 Self::InvalidSelect => "Invalid select or include",
163 Self::RequiredFieldMissing => "Required field missing",
164 Self::UniqueConstraint => "Unique constraint violation",
165 Self::ForeignKeyConstraint => "Foreign key constraint violation",
166 Self::CheckConstraint => "Check constraint violation",
167 Self::NotNullConstraint => "Not null constraint violation",
168 Self::ConnectionFailed => "Database connection failed",
169 Self::PoolExhausted => "Connection pool exhausted",
170 Self::ConnectionTimeout => "Connection timeout",
171 Self::AuthenticationFailed => "Authentication failed",
172 Self::SslError => "SSL/TLS error",
173 Self::TransactionFailed => "Transaction failed",
174 Self::Deadlock => "Deadlock detected",
175 Self::SerializationFailure => "Serialization failure",
176 Self::TransactionClosed => "Transaction already closed",
177 Self::QueryTimeout => "Query timeout",
178 Self::SqlSyntax => "SQL syntax error",
179 Self::InvalidParameter => "Invalid parameter",
180 Self::QueryTooComplex => "Query too complex",
181 Self::DatabaseError => "Database error",
182 Self::InvalidDataType => "Invalid data type",
183 Self::SerializationError => "Serialization error",
184 Self::DeserializationError => "Deserialization error",
185 Self::DataTruncation => "Data truncation",
186 Self::InvalidConfiguration => "Invalid configuration",
187 Self::MissingConfiguration => "Missing configuration",
188 Self::InvalidConnectionString => "Invalid connection string",
189 Self::Internal => "Internal error",
190 Self::Unknown => "Unknown error",
191 }
192 }
193
194 pub fn docs_url(&self) -> String {
196 format!("https://prax.rs/docs/errors/{}", self.code())
197 }
198}
199
200impl fmt::Display for ErrorCode {
201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202 write!(f, "{}", self.code())
203 }
204}
205
206#[derive(Debug, Clone)]
208pub struct Suggestion {
209 pub text: String,
211 pub code: Option<String>,
213}
214
215impl Suggestion {
216 pub fn new(text: impl Into<String>) -> Self {
218 Self {
219 text: text.into(),
220 code: None,
221 }
222 }
223
224 pub fn with_code(mut self, code: impl Into<String>) -> Self {
226 self.code = Some(code.into());
227 self
228 }
229}
230
231#[derive(Debug, Clone, Default)]
233pub struct ErrorContext {
234 pub operation: Option<String>,
236 pub model: Option<String>,
238 pub field: Option<String>,
240 pub sql: Option<String>,
242 pub suggestions: Vec<Suggestion>,
244 pub help: Option<String>,
246 pub related: Vec<String>,
248}
249
250impl ErrorContext {
251 pub fn new() -> Self {
253 Self::default()
254 }
255
256 pub fn operation(mut self, op: impl Into<String>) -> Self {
258 self.operation = Some(op.into());
259 self
260 }
261
262 pub fn model(mut self, model: impl Into<String>) -> Self {
264 self.model = Some(model.into());
265 self
266 }
267
268 pub fn field(mut self, field: impl Into<String>) -> Self {
270 self.field = Some(field.into());
271 self
272 }
273
274 pub fn sql(mut self, sql: impl Into<String>) -> Self {
276 self.sql = Some(sql.into());
277 self
278 }
279
280 pub fn suggestion(mut self, suggestion: Suggestion) -> Self {
282 self.suggestions.push(suggestion);
283 self
284 }
285
286 pub fn suggest(mut self, text: impl Into<String>) -> Self {
288 self.suggestions.push(Suggestion::new(text));
289 self
290 }
291
292 pub fn help(mut self, help: impl Into<String>) -> Self {
294 self.help = Some(help.into());
295 self
296 }
297}
298
299#[derive(Error, Debug)]
301pub struct QueryError {
302 pub code: ErrorCode,
304 pub message: String,
306 pub context: ErrorContext,
308 #[source]
310 pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
311 sqlstate: Option<String>,
314}
315
316impl fmt::Display for QueryError {
317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318 write!(f, "[{}] {}", self.code.code(), self.message)
319 }
320}
321
322impl QueryError {
323 pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
325 Self {
326 code,
327 message: message.into(),
328 context: ErrorContext::default(),
329 source: None,
330 sqlstate: None,
331 }
332 }
333
334 pub fn sqlstate(&self) -> Option<&str> {
343 self.sqlstate.as_deref()
344 }
345
346 pub fn with_sqlstate(mut self, sqlstate: impl Into<String>) -> Self {
349 self.sqlstate = Some(sqlstate.into());
350 self
351 }
352
353 pub fn with_context(mut self, operation: impl Into<String>) -> Self {
355 self.context.operation = Some(operation.into());
356 self
357 }
358
359 pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
361 self.context.suggestions.push(Suggestion::new(suggestion));
362 self
363 }
364
365 pub fn with_code_suggestion(
367 mut self,
368 text: impl Into<String>,
369 code: impl Into<String>,
370 ) -> Self {
371 self.context
372 .suggestions
373 .push(Suggestion::new(text).with_code(code));
374 self
375 }
376
377 pub fn with_help(mut self, help: impl Into<String>) -> Self {
379 self.context.help = Some(help.into());
380 self
381 }
382
383 pub fn with_model(mut self, model: impl Into<String>) -> Self {
385 self.context.model = Some(model.into());
386 self
387 }
388
389 pub fn with_field(mut self, field: impl Into<String>) -> Self {
391 self.context.field = Some(field.into());
392 self
393 }
394
395 pub fn with_sql(mut self, sql: impl Into<String>) -> Self {
397 self.context.sql = Some(sql.into());
398 self
399 }
400
401 pub fn with_source<E: std::error::Error + Send + Sync + 'static>(mut self, source: E) -> Self {
403 self.source = Some(Box::new(source));
404 self
405 }
406
407 pub fn not_found(model: impl Into<String>) -> Self {
411 let model = model.into();
412 Self::new(
413 ErrorCode::RecordNotFound,
414 format!("No {} record found matching the query", model),
415 )
416 .with_model(&model)
417 .with_suggestion(format!("Verify the {} exists before querying", model))
418 .with_code_suggestion(
419 "Use findFirst() instead to get None instead of an error",
420 format!(
421 "client.{}().find_first().r#where(...).exec().await",
422 model.to_lowercase()
423 ),
424 )
425 }
426
427 pub fn not_unique(model: impl Into<String>) -> Self {
429 let model = model.into();
430 Self::new(
431 ErrorCode::NotUnique,
432 format!("Expected unique {} record but found multiple", model),
433 )
434 .with_model(&model)
435 .with_suggestion("Add more specific filters to narrow down to a single record")
436 .with_suggestion("Use find_many() if you expect multiple results")
437 }
438
439 pub fn constraint_violation(model: impl Into<String>, message: impl Into<String>) -> Self {
441 let model = model.into();
442 let message = message.into();
443 Self::new(
444 ErrorCode::UniqueConstraint,
445 format!("Constraint violation on {}: {}", model, message),
446 )
447 .with_model(&model)
448 }
449
450 pub fn unique_violation(model: impl Into<String>, field: impl Into<String>) -> Self {
452 let model = model.into();
453 let field = field.into();
454 Self::new(
455 ErrorCode::UniqueConstraint,
456 format!("Unique constraint violated on {}.{}", model, field),
457 )
458 .with_model(&model)
459 .with_field(&field)
460 .with_suggestion(format!("A record with this {} already exists", field))
461 .with_code_suggestion(
462 "Use upsert() to update if exists, create if not",
463 format!(
464 "client.{}().upsert()\n .r#where({}::{}::equals(value))\n .create(...)\n .update(...)\n .exec().await",
465 model.to_lowercase(), model.to_lowercase(), field
466 ),
467 )
468 }
469
470 pub fn foreign_key_violation(model: impl Into<String>, relation: impl Into<String>) -> Self {
472 let model = model.into();
473 let relation = relation.into();
474 Self::new(
475 ErrorCode::ForeignKeyConstraint,
476 format!("Foreign key constraint violated: {} -> {}", model, relation),
477 )
478 .with_model(&model)
479 .with_field(&relation)
480 .with_suggestion(format!(
481 "Ensure the related {} record exists before creating this {}",
482 relation, model
483 ))
484 .with_suggestion("Check for typos in the relation ID")
485 }
486
487 pub fn not_null_violation(model: impl Into<String>, field: impl Into<String>) -> Self {
489 let model = model.into();
490 let field = field.into();
491 Self::new(
492 ErrorCode::NotNullConstraint,
493 format!("Cannot set {}.{} to null - field is required", model, field),
494 )
495 .with_model(&model)
496 .with_field(&field)
497 .with_suggestion(format!("Provide a value for the {} field", field))
498 .with_help("Make the field optional in your schema if null should be allowed")
499 }
500
501 pub fn invalid_input(field: impl Into<String>, message: impl Into<String>) -> Self {
503 let field = field.into();
504 let message = message.into();
505 Self::new(
506 ErrorCode::InvalidParameter,
507 format!("Invalid input for {}: {}", field, message),
508 )
509 .with_field(&field)
510 }
511
512 pub fn connection(message: impl Into<String>) -> Self {
514 let message = message.into();
515 Self::new(
516 ErrorCode::ConnectionFailed,
517 format!("Connection error: {}", message),
518 )
519 .with_suggestion("Check that the database server is running")
520 .with_suggestion("Verify the connection URL is correct")
521 .with_suggestion("Check firewall settings allow the connection")
522 }
523
524 pub fn connection_timeout(duration_ms: u64) -> Self {
526 Self::new(
527 ErrorCode::ConnectionTimeout,
528 format!("Connection timed out after {}ms", duration_ms),
529 )
530 .with_suggestion("Increase the connect_timeout in your connection string")
531 .with_suggestion("Check network connectivity to the database server")
532 .with_code_suggestion(
533 "Add connect_timeout to your connection URL",
534 "postgres://user:pass@host/db?connect_timeout=30",
535 )
536 }
537
538 pub fn pool_exhausted(max_connections: u32) -> Self {
540 Self::new(
541 ErrorCode::PoolExhausted,
542 format!("Connection pool exhausted (max {} connections)", max_connections),
543 )
544 .with_suggestion("Increase max_connections in pool configuration")
545 .with_suggestion("Ensure connections are being released properly")
546 .with_suggestion("Check for connection leaks in your application")
547 .with_help("Consider using connection pooling middleware like PgBouncer for high-traffic applications")
548 }
549
550 pub fn authentication_failed(message: impl Into<String>) -> Self {
552 let message = message.into();
553 Self::new(
554 ErrorCode::AuthenticationFailed,
555 format!("Authentication failed: {}", message),
556 )
557 .with_suggestion("Check username and password in connection string")
558 .with_suggestion("Verify the user has permission to access the database")
559 .with_suggestion("Check pg_hba.conf (PostgreSQL) or user privileges (MySQL)")
560 }
561
562 pub fn timeout(duration_ms: u64) -> Self {
564 Self::new(
565 ErrorCode::QueryTimeout,
566 format!("Query timed out after {}ms", duration_ms),
567 )
568 .with_suggestion("Optimize the query to run faster")
569 .with_suggestion("Add indexes to improve query performance")
570 .with_suggestion("Increase the query timeout if the query is expected to be slow")
571 .with_help("Consider paginating large result sets")
572 }
573
574 pub fn transaction(message: impl Into<String>) -> Self {
576 let message = message.into();
577 Self::new(
578 ErrorCode::TransactionFailed,
579 format!("Transaction error: {}", message),
580 )
581 }
582
583 pub fn deadlock() -> Self {
585 Self::new(
586 ErrorCode::Deadlock,
587 "Deadlock detected - transaction was rolled back".to_string(),
588 )
589 .with_suggestion("Retry the transaction")
590 .with_suggestion("Access tables in a consistent order across transactions")
591 .with_suggestion("Keep transactions short to reduce lock contention")
592 .with_help("Deadlocks occur when two transactions wait for each other's locks")
593 }
594
595 pub fn stale_plan(message: impl Into<String>) -> Self {
608 Self::new(ErrorCode::SerializationFailure, message.into())
609 .with_suggestion("Retry the query; the cached plan will be re-prepared")
610 .with_help(
611 "A prepared statement was reused after DDL changed a referenced table's result \
612 columns. This is transient and clears on re-prepare.",
613 )
614 }
615
616 pub fn sql_syntax(message: impl Into<String>, sql: impl Into<String>) -> Self {
618 let message = message.into();
619 let sql = sql.into();
620 Self::new(
621 ErrorCode::SqlSyntax,
622 format!("SQL syntax error: {}", message),
623 )
624 .with_sql(&sql)
625 .with_suggestion("Check the generated SQL for errors")
626 .with_help("This is likely a bug in Prax - please report it")
627 }
628
629 pub fn serialization(message: impl Into<String>) -> Self {
631 Self::new(ErrorCode::SerializationError, message.into())
632 }
633
634 pub fn deserialization(message: impl Into<String>) -> Self {
636 let message = message.into();
637 Self::new(
638 ErrorCode::DeserializationError,
639 format!("Failed to deserialize result: {}", message),
640 )
641 .with_suggestion("Check that the model matches the database schema")
642 .with_suggestion("Ensure data types are compatible")
643 }
644
645 pub fn database(message: impl Into<String>) -> Self {
647 let message = message.into();
648 Self::new(ErrorCode::DatabaseError, message)
649 .with_suggestion("Check the database logs for more details")
650 }
651
652 pub fn internal(message: impl Into<String>) -> Self {
654 let message = message.into();
655 Self::new(ErrorCode::Internal, format!("Internal error: {}", message))
656 .with_help("This is likely a bug in Prax ORM - please report it at https://github.com/quinnjr/prax/issues")
657 }
658
659 pub fn unsupported(message: impl Into<String>) -> Self {
661 let message = message.into();
662 Self::new(
663 ErrorCode::InvalidConfiguration,
664 format!("Unsupported: {}", message),
665 )
666 .with_help("This operation is not supported by the current database driver")
667 }
668
669 pub fn is_not_found(&self) -> bool {
673 self.code == ErrorCode::RecordNotFound
674 }
675
676 pub fn is_constraint_violation(&self) -> bool {
678 matches!(
679 self.code,
680 ErrorCode::UniqueConstraint
681 | ErrorCode::ForeignKeyConstraint
682 | ErrorCode::CheckConstraint
683 | ErrorCode::NotNullConstraint
684 )
685 }
686
687 pub fn is_timeout(&self) -> bool {
689 matches!(
690 self.code,
691 ErrorCode::QueryTimeout | ErrorCode::ConnectionTimeout
692 )
693 }
694
695 pub fn is_connection_error(&self) -> bool {
697 matches!(
698 self.code,
699 ErrorCode::ConnectionFailed
700 | ErrorCode::PoolExhausted
701 | ErrorCode::ConnectionTimeout
702 | ErrorCode::AuthenticationFailed
703 | ErrorCode::SslError
704 )
705 }
706
707 pub fn is_retryable(&self) -> bool {
709 matches!(
710 self.code,
711 ErrorCode::ConnectionTimeout
712 | ErrorCode::PoolExhausted
713 | ErrorCode::QueryTimeout
714 | ErrorCode::Deadlock
715 | ErrorCode::SerializationFailure
716 )
717 }
718
719 pub fn error_code(&self) -> &ErrorCode {
723 &self.code
724 }
725
726 pub fn docs_url(&self) -> String {
728 self.code.docs_url()
729 }
730
731 pub fn display_full(&self) -> String {
733 let mut output = String::new();
734
735 output.push_str(&format!("Error [{}]: {}\n", self.code.code(), self.message));
737
738 if let Some(ref op) = self.context.operation {
740 output.push_str(&format!(" → While: {}\n", op));
741 }
742 if let Some(ref model) = self.context.model {
743 output.push_str(&format!(" → Model: {}\n", model));
744 }
745 if let Some(ref field) = self.context.field {
746 output.push_str(&format!(" → Field: {}\n", field));
747 }
748
749 if let Some(ref sql) = self.context.sql {
751 let sql_display = if sql.len() > 200 {
752 format!("{}...", &sql[..200])
753 } else {
754 sql.clone()
755 };
756 output.push_str(&format!(" → SQL: {}\n", sql_display));
757 }
758
759 if !self.context.suggestions.is_empty() {
761 output.push_str("\nSuggestions:\n");
762 for (i, suggestion) in self.context.suggestions.iter().enumerate() {
763 output.push_str(&format!(" {}. {}\n", i + 1, suggestion.text));
764 if let Some(ref code) = suggestion.code {
765 output.push_str(&format!(
766 " ```\n {}\n ```\n",
767 code.replace('\n', "\n ")
768 ));
769 }
770 }
771 }
772
773 if let Some(ref help) = self.context.help {
775 output.push_str(&format!("\nHelp: {}\n", help));
776 }
777
778 output.push_str(&format!("\nMore info: {}\n", self.docs_url()));
780
781 output
782 }
783
784 pub fn display_colored(&self) -> String {
786 let mut output = String::new();
787
788 output.push_str(&format!(
790 "\x1b[1;31mError [{}]\x1b[0m: \x1b[1m{}\x1b[0m\n",
791 self.code.code(),
792 self.message
793 ));
794
795 if let Some(ref op) = self.context.operation {
797 output.push_str(&format!(" \x1b[2m→ While:\x1b[0m {}\n", op));
798 }
799 if let Some(ref model) = self.context.model {
800 output.push_str(&format!(" \x1b[2m→ Model:\x1b[0m {}\n", model));
801 }
802 if let Some(ref field) = self.context.field {
803 output.push_str(&format!(" \x1b[2m→ Field:\x1b[0m {}\n", field));
804 }
805
806 if !self.context.suggestions.is_empty() {
808 output.push_str("\n\x1b[1;33mSuggestions:\x1b[0m\n");
809 for (i, suggestion) in self.context.suggestions.iter().enumerate() {
810 output.push_str(&format!(
811 " \x1b[33m{}.\x1b[0m {}\n",
812 i + 1,
813 suggestion.text
814 ));
815 if let Some(ref code) = suggestion.code {
816 output.push_str(&format!(
817 " \x1b[2m```\x1b[0m\n \x1b[36m{}\x1b[0m\n \x1b[2m```\x1b[0m\n",
818 code.replace('\n', "\n ")
819 ));
820 }
821 }
822 }
823
824 if let Some(ref help) = self.context.help {
826 output.push_str(&format!("\n\x1b[1;36mHelp:\x1b[0m {}\n", help));
827 }
828
829 output.push_str(&format!(
831 "\n\x1b[2mMore info:\x1b[0m \x1b[4;34m{}\x1b[0m\n",
832 self.docs_url()
833 ));
834
835 output
836 }
837}
838
839pub trait IntoQueryError {
841 fn into_query_error(self) -> QueryError;
843}
844
845impl<E: std::error::Error + Send + Sync + 'static> IntoQueryError for E {
846 fn into_query_error(self) -> QueryError {
847 QueryError::internal(self.to_string()).with_source(self)
848 }
849}
850
851#[macro_export]
853macro_rules! query_error {
854 ($code:expr, $msg:expr) => {
855 $crate::error::QueryError::new($code, $msg)
856 };
857 ($code:expr, $msg:expr, $($key:ident = $value:expr),+ $(,)?) => {{
858 let mut err = $crate::error::QueryError::new($code, $msg);
859 $(
860 err = err.$key($value);
861 )+
862 err
863 }};
864}
865
866#[cfg(test)]
867mod tests {
868 use super::*;
869
870 #[test]
871 fn sqlstate_is_none_unless_set() {
872 assert_eq!(QueryError::database("boom").sqlstate(), None);
873 let err = QueryError::database("could not obtain lock").with_sqlstate("55P03");
874 assert_eq!(err.sqlstate(), Some("55P03"));
875 assert_eq!(err.code, ErrorCode::DatabaseError);
877 assert!(
878 err.to_string().ends_with("] could not obtain lock"),
879 "{err}"
880 );
881 }
882
883 #[test]
884 fn test_error_code_format() {
885 assert_eq!(ErrorCode::RecordNotFound.code(), "P1001");
886 assert_eq!(ErrorCode::UniqueConstraint.code(), "P2001");
887 assert_eq!(ErrorCode::ConnectionFailed.code(), "P3001");
888 }
889
890 #[test]
891 fn test_not_found_error() {
892 let err = QueryError::not_found("User");
893 assert!(err.is_not_found());
894 assert!(err.message.contains("User"));
895 assert!(!err.context.suggestions.is_empty());
896 }
897
898 #[test]
899 fn test_unique_violation_error() {
900 let err = QueryError::unique_violation("User", "email");
901 assert!(err.is_constraint_violation());
902 assert_eq!(err.context.model, Some("User".to_string()));
903 assert_eq!(err.context.field, Some("email".to_string()));
904 }
905
906 #[test]
907 fn test_timeout_error() {
908 let err = QueryError::timeout(5000);
909 assert!(err.is_timeout());
910 assert!(err.message.contains("5000"));
911 }
912
913 #[test]
914 fn test_error_with_context() {
915 let err = QueryError::not_found("User")
916 .with_context("Finding user by email")
917 .with_suggestion("Use a different query method");
918
919 assert_eq!(
920 err.context.operation,
921 Some("Finding user by email".to_string())
922 );
923 assert!(err.context.suggestions.len() >= 2); }
925
926 #[test]
927 fn test_retryable_errors() {
928 assert!(QueryError::timeout(1000).is_retryable());
929 assert!(QueryError::deadlock().is_retryable());
930 assert!(QueryError::pool_exhausted(10).is_retryable());
931 assert!(!QueryError::not_found("User").is_retryable());
932 }
933
934 #[test]
935 fn test_stale_plan_is_retryable() {
936 let err = QueryError::stale_plan("cached plan must not change result type");
940 assert_eq!(err.code, ErrorCode::SerializationFailure);
941 assert!(err.is_retryable());
942 }
943
944 #[test]
945 fn test_connection_errors() {
946 assert!(QueryError::connection("failed").is_connection_error());
947 assert!(QueryError::authentication_failed("bad password").is_connection_error());
948 assert!(QueryError::pool_exhausted(10).is_connection_error());
949 }
950
951 #[test]
952 fn test_display_full() {
953 let err = QueryError::unique_violation("User", "email").with_context("Creating new user");
954
955 let output = err.display_full();
956 assert!(output.contains("P2001"));
957 assert!(output.contains("User"));
958 assert!(output.contains("email"));
959 assert!(output.contains("Suggestions"));
960 }
961
962 #[test]
963 fn test_docs_url() {
964 let err = QueryError::not_found("User");
965 assert!(err.docs_url().contains("P1001"));
966 }
967
968 #[test]
969 fn test_error_macro() {
970 let err = query_error!(
971 ErrorCode::InvalidParameter,
972 "Invalid email format",
973 with_field = "email",
974 with_suggestion = "Use a valid email address"
975 );
976
977 assert_eq!(err.code, ErrorCode::InvalidParameter);
978 assert_eq!(err.context.field, Some("email".to_string()));
979 }
980
981 #[test]
982 fn test_suggestion_with_code() {
983 let err = QueryError::not_found("User")
984 .with_code_suggestion("Try this instead", "client.user().find_first()");
985
986 let suggestion = err.context.suggestions.last().unwrap();
987 assert!(suggestion.code.is_some());
988 }
989
990 #[test]
991 fn with_source_populates_std_error_source_chain() {
992 use std::error::Error;
993 let io_err = std::io::Error::new(std::io::ErrorKind::ConnectionAborted, "boom");
994 let q = QueryError::connection("could not connect").with_source(io_err);
995 let src = q
996 .source()
997 .expect("source() should return the chained error");
998 assert!(src.to_string().contains("boom"));
999 }
1000}