radical icon indicating copy to clipboard operation
radical copied to clipboard

More idiomatic errors.

Open SpBills opened this issue 4 years ago • 0 comments

Program Version.

Pre-alpha

Problem Description.

Errors can be much more idiomatic and understandable.

Just in case you've never heard of this feature, see for instance, in another (proprietary) software of mine,

#[derive(Debug, Responder)]
pub enum HttpError {
    NotFound(Json<u32>),
    InternalServerError(Json<u32>)
}

impl From<DieselError> for HttpError {
    fn from(err: DieselError) -> Self {
        match err {
            diesel::NotFound => HttpError::NotFound(Json(404)),
            _ => HttpError::InternalServerError(Json(500))
        }
    }
}

Since there is a from for this error, the error can be automatically casted on lift.

Take for instance this controller:

#[get("/<id>")]
pub fn get_one(id: i32, db: DbPooll) -> Result<Json<RelationalCourse>, HttpError> {
    Ok(Json(CourseModel::join(id, &db)?))
}

CourseModel::join(...) returns a Result<RelationalCourse, DieselError> but because of the From for type DieselError implemented on the HttpError enum, it automatically casts it on lift.

Problem Solutions.

Add a From impl for a custom error type which matches all error types we're catching to an HTTP status code according to the type of error.

Other Details.

You can find this in here. This should pretty much all be replaced.

SpBills avatar Jun 24 '21 01:06 SpBills