conductor/src/errors.rs

95 lines
2.9 KiB
Rust

/*
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::convert::From;
use actix_web::http;
use actix_web::http::StatusCode;
use actix_web::HttpResponse;
use actix_web::HttpResponseBuilder;
use actix_web::ResponseError;
use derive_more::{Display, Error};
use serde::{Deserialize, Serialize};
use url::ParseError;
#[derive(Debug, Display, PartialEq, Eq, Error)]
#[cfg(not(tarpaulin_include))]
#[allow(dead_code)]
pub enum ServiceError {
#[display(fmt = "unauthorized")]
Unauthorized,
#[display(fmt = "internal server error")]
InternalServerError,
#[display(
fmt = "This server is is closed for registration. Contact admin if this is unexpecter"
)]
ClosedForRegistration,
#[display(fmt = "The value you entered for URL is not a URL")] //405j
NotAUrl,
#[display(fmt = "Wrong password")]
WrongPassword,
}
#[derive(Serialize, Deserialize)]
#[cfg(not(tarpaulin_include))]
pub struct ErrorToResponse {
pub error: String,
}
#[cfg(not(tarpaulin_include))]
impl ResponseError for ServiceError {
#[cfg(not(tarpaulin_include))]
fn error_response(&self) -> HttpResponse {
HttpResponseBuilder::new(self.status_code())
.append_header((
http::header::CONTENT_TYPE,
"application/json; charset=UTF-8",
))
.body(
serde_json::to_string(&ErrorToResponse {
error: self.to_string(),
})
.unwrap(),
)
}
#[cfg(not(tarpaulin_include))]
fn status_code(&self) -> StatusCode {
match self {
ServiceError::ClosedForRegistration => StatusCode::FORBIDDEN,
ServiceError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
ServiceError::NotAUrl => StatusCode::BAD_REQUEST,
ServiceError::WrongPassword => StatusCode::UNAUTHORIZED,
ServiceError::Unauthorized => StatusCode::UNAUTHORIZED,
}
}
}
impl From<ParseError> for ServiceError {
#[cfg(not(tarpaulin_include))]
fn from(_: ParseError) -> ServiceError {
ServiceError::NotAUrl
}
}
#[cfg(not(tarpaulin_include))]
pub type ServiceResult<V> = std::result::Result<V, ServiceError>;