Skip to content

Simpler matching of DatabaseErrors #4169

@kellianb

Description

@kellianb

I have found these related issues/pull requests

The only somewhat related issue I was able to find is this one: #658

Description

Matching sqlx errors and database errors currently requires either writing match statements with complicated and lengthy clauses, or nested match statements, which are both unergonomic.

This proposal attempts to address this by adding a new method to the 'DatabaseError' trait which allows matching the ErrorKind and constraint name in one go. This would make error matching code simpler and more readable.

Prefered solution

Here is an example implementation

pub trait DatabaseError: 'static + Send + Sync + StdError {
    fn matches(&self, kind: ErrorKind, constraint_name: &str) -> bool {
        self.kind() == kind && self.constraint_name() == Some(constraint_name)
    }
}

Example use:

if (dbe.matches(ErrorKind::ForeignKeyViolation, "user_id")) {
// do something here....
}

Is this a breaking change? Why or why not?

This would not modify any existing methods of the DatabaseError trait, it would therefore not be a breaking change.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions