{"record":{"id":"933c772cf2972f05","repo":"transact-rs/sqlx","slug":"downcast-to-wrong-databaseerror-type-original-err","errorCode":null,"errorMessage":"downcast to wrong DatabaseError type; original error: {self}","messagePattern":"downcast to wrong DatabaseError type; original error: (.+?)","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"sqlx-core/src/error.rs","lineNumber":286,"sourceCode":"\n    /// Returns whether the error kind is a violation of a check.\n    fn is_check_violation(&self) -> bool {\n        matches!(self.kind(), ErrorKind::CheckViolation)\n    }\n}\n\nimpl dyn DatabaseError {\n    /// Downcast a reference to this generic database error to a specific\n    /// database error type.\n    ///\n    /// # Panics\n    ///\n    /// Panics if the database error type is not `E`. This is a deliberate contrast from\n    /// `Error::downcast_ref` which returns `Option<&E>`. In normal usage, you should know the\n    /// specific error type. In other cases, use `try_downcast_ref`.\n    pub fn downcast_ref<E: DatabaseError>(&self) -> &E {\n        self.try_downcast_ref().unwrap_or_else(|| {\n            panic!(\"downcast to wrong DatabaseError type; original error: {self}\")\n        })\n    }\n\n    /// Downcast this generic database error to a specific database error type.\n    ///\n    /// # Panics\n    ///\n    /// Panics if the database error type is not `E`. This is a deliberate contrast from\n    /// `Error::downcast` which returns `Option<E>`. In normal usage, you should know the\n    /// specific error type. In other cases, use `try_downcast`.\n    pub fn downcast<E: DatabaseError>(self: Box<Self>) -> Box<E> {\n        self.try_downcast()\n            .unwrap_or_else(|e| panic!(\"downcast to wrong DatabaseError type; original error: {e}\"))\n    }\n\n    /// Downcast a reference to this generic database error to a specific\n    /// database error type.\n    #[inline]","sourceCodeStart":268,"sourceCodeEnd":304,"githubUrl":"https://github.com/transact-rs/sqlx/blob/03af8bcc5711a1935580a54bea249c219a0c217d/sqlx-core/src/error.rs#L268-L304","documentation":"DatabaseError::downcast_ref() (sqlx-core/src/error.rs) panics when the caller asks for a concrete database error type E but the stored error is of a different backend's type. Unlike try_downcast_ref (which returns Option), this is the infallible variant meant for code that already knows the backend; mismatch indicates a logic bug, so sqlx panics and prints the original error.","triggerScenarios":"Calling `err.as_database_error().unwrap().downcast_ref::<PgDatabaseError>()` (or MySqlDatabaseError, SqliteError...) on an error produced by a different driver — e.g. handling errors from a multi-backend `AnyPool`, or a generic error-handling path shared across Postgres and MySQL pools.","commonSituations":"Code written for PgPool later reused with a SqlitePool or AnyPool; CI running against a different database than production; match arms that call downcast_ref without first checking which backend produced the error.","solutions":["Use `try_downcast_ref::<E>()` and handle the None case instead of the panicking variant.","Check the backend before downcasting (e.g. keep separate error-handling paths per pool type, or match on the connection/pool type).","If using AnyPool, downcast to `any::AnyDatabaseError` style handling or use backend-specific pools where you know the error type."],"exampleFix":"// before\nlet pg_err = db_err.downcast_ref::<PgDatabaseError>();\n\n// after\nif let Some(pg_err) = db_err.try_downcast_ref::<PgDatabaseError>() {\n    handle_pg(pg_err);\n} else {\n    handle_generic(db_err);\n}","handlingStrategy":"type-guard","validationCode":null,"typeGuard":"fn as_pg_error(db_err: &dyn sqlx::error::DatabaseError) -> Option<&sqlx::postgres::PgDatabaseError> {\n    db_err.try_downcast_ref::<sqlx::postgres::PgDatabaseError>()\n}","tryCatchPattern":"// Downcasts are infallible-looking; use the Try variants instead of catching panics:\nmatch db_err.try_downcast_ref::<PgDatabaseError>() {\n    Some(e) => handle_pg(e),\n    None => handle_generic(db_err),\n}","preventionTips":["Prefer try_downcast_ref/try_downcast over the panicking variants","Keep per-backend error handling next to the pool that produced the error","In multi-backend code, dispatch on backend before downcasting"],"tags":["panic","downcast","database-error","sqlx"],"backgroundTag":"wrong-error-downcast","analyzedSha":"03af8bcc5711a1935580a54bea249c219a0c217d","analyzedAt":"2026-09-03T15:01:28.752Z","contentChangedAt":"2026-09-03T15:01:28.752Z","schemaVersion":2},"datasetVersion":"2026-09-10T17:17:09.494Z"}