poem icon indicating copy to clipboard operation
poem copied to clipboard

Create a derive for custom errors

Open TheCataliasTNT2k opened this issue 2 years ago • 3 comments

Description of the feature

You can create request params by deriving from Object but you can not create custom errors yet, which are shown as errors in OpenApi and can be returned directly.

TheCataliasTNT2k avatar Dec 28 '22 00:12 TheCataliasTNT2k

Maybe you can refer to this, ErrResponse is a custom error.

https://github.com/poem-web/poem/blob/7ada5b69c94c0a98ddff64172703ed61c3386fdf/poem-openapi/tests/response.rs#L402

sunli829 avatar Dec 29 '22 02:12 sunli829

No, that does not work. I tried your solution, but no errors within the response sections (apart from the error codes).

What I did before:

#[derive(ApiResponse)]
enum UpdateUserResp {
    /// everything is fine
    #[oai(status = 200)]
    Ok,

    /// you are not logged in
    #[oai(status = 401)]
    #[allow(dead_code)]
    Unauthorized,

    /// you are not allowed to do that
    #[oai(status = 403)]
    #[allow(dead_code)]
    Forbidden,

    /// this user does not exist
    #[oai(status = 404)]
    NotFound,

    /// this username is already taken
    #[oai(status = 429)]
    UserNameConflict(Json<UserNameConflictError>),

    /// something went wrong
    #[oai(status = 500)]
    #[allow(dead_code)]
    InternalServerError,
}

I added all errors to my response and returned them. It would be great, if you can do something like this: #[oai(status = 401, error = true)] and

#[derive(Debug, thiserror::Error, poem::ErrorObject)]
#[error("{message}")]
struct UserNameConflictError {
    message: String,
}

impl ResponseError for UserNameConflictError {
    fn status(&self) -> StatusCode {
        StatusCode::CONFLICT
    }
}

to create an error, that is actually shown as error like this: 2022-12-29_15-25

Furthermore, it would be great, if the user can provide examples, like shown above. This should work for errors an non error responses as well.

TheCataliasTNT2k avatar Dec 29 '22 14:12 TheCataliasTNT2k

I asked the creator of the API shown above: He does not create custom errors, but uses the example feature, which can be used for requests as well to archive that. So this is not a feature of Swagger directly, but a hack. The errors are not shown down below the other stuff nevertheless.

TheCataliasTNT2k avatar Jan 08 '23 23:01 TheCataliasTNT2k