rusty-bever/src/errors.rs

69 lines
1.9 KiB
Rust
Raw Normal View History

2021-08-21 15:58:51 +02:00
use std::io;
2021-08-22 16:45:01 +02:00
use rocket::{
http::Status,
request::Request,
response::{self, Responder, Response},
};
2021-08-21 18:05:16 +02:00
#[derive(Debug)]
2021-08-27 08:50:48 +02:00
pub enum RbError
2021-08-22 16:45:01 +02:00
{
2021-08-27 08:50:48 +02:00
AuthUnknownUser,
AuthBlockedUser,
AuthInvalidPassword,
AuthUnauthorized,
AuthTokenExpired,
AuthRefreshTokenExpired,
AuthInvalidRefreshToken,
AuthDuplicateRefreshToken,
Custom(&'static str),
2021-08-21 18:05:16 +02:00
AdminCreationError,
2021-08-22 10:42:58 +02:00
DBError,
2021-08-22 22:35:07 +02:00
DuplicateUser,
2021-08-20 23:09:22 +02:00
}
2021-08-21 15:58:51 +02:00
2021-08-27 08:50:48 +02:00
impl RbError {
pub fn status(&self) -> Status {
Status::NotFound
}
pub fn message(&self) -> &'static str {
match self {
}
}
}
2021-08-22 16:45:01 +02:00
impl<'r> Responder<'r, 'static> for RBError
{
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static>
{
2021-08-27 08:50:48 +02:00
let (status, message): (Status, &'static str) = match self {
2021-08-21 16:45:41 +02:00
RBError::UnknownUser => (Status::NotFound, "Unknown user"),
2021-08-21 18:05:16 +02:00
RBError::BlockedUser => (Status::Unauthorized, "This user is blocked"),
2021-08-21 16:45:41 +02:00
RBError::InvalidPassword => (Status::Unauthorized, "Invalid password"),
RBError::Unauthorized => (Status::Unauthorized, "Unauthorized"),
RBError::JWTTokenExpired => (Status::Unauthorized, "Token expired"),
2021-08-21 21:42:36 +02:00
RBError::JWTCreationError | RBError::MissingJWTKey => {
(Status::InternalServerError, "Failed to create tokens.")
}
2021-08-22 15:50:58 +02:00
RBError::InvalidRefreshToken | RBError::DuplicateRefreshToken => {
(Status::Unauthorized, "Invalid refresh token.")
}
2021-08-22 22:35:07 +02:00
RBError::DuplicateUser => (Status::Conflict, "User already exists"),
2021-08-21 21:42:36 +02:00
_ => (Status::InternalServerError, "Internal server error"),
2021-08-21 15:58:51 +02:00
};
2021-08-21 16:45:41 +02:00
let mut res = Response::new();
2021-08-21 15:58:51 +02:00
res.set_status(status);
res.set_sized_body(message.len(), io::Cursor::new(message));
Ok(res)
}
}
pub type Result<T> = std::result::Result<T, RBError>;