使Rust中的包装错误类型更易于阅读

时间:2019-07-15 19:49:51

标签: sqlite error-handling rust pattern-matching

Rusqlite通过SqliteFailure暴露来自sqlite的错误。在ConstraintVialotation上进行匹配的过程类似于:

match error {
    // when inserting and document exists
    SqliteFailure(
        LibSqliteError {
            code: ConstraintViolation,
            extended_code: SQLITE_CONSTRAINT_PRIMARYKEY,
        },
        _,
    ) => { /* handle error */ }
}

这很冗长。 Issue 293 at rusqlite建议:

match err {
    SqliteFailure(err, _desc) => {
        if err.code == ConstraintViolation 
            && err.extended_code == SQLITE_CONSTRAINT_PRIMARYKEY 
        { /* handle error */ }
    }
}

仍然很冗长。我天真地尝试使用内容为类型别名,这是不允许的:

type PrimaryKeyContraint = SqliteFailure(LibSqliteError { code: ConstraintViolation, extended_code: 1555 }, _);

是否存在将匹配逻辑移至函数的替代方法

fn is_primary_key_constraint(error: &rusqlite::Error) -> bool

使匹配的包装错误更易读?

0 个答案:

没有答案