rqbit/crates/librqbit/src/api_error.rs

162 lines
4.4 KiB
Rust
Raw Normal View History

2022-12-08 20:43:02 +00:00
use axum::response::{IntoResponse, Response};
use http::StatusCode;
2022-12-08 21:10:34 +00:00
use serde::{Serialize, Serializer};
2022-12-08 15:40:29 +00:00
// Convenience error type.
#[derive(Debug)]
pub struct ApiError {
status: Option<StatusCode>,
kind: ApiErrorKind,
plaintext: bool,
2022-12-08 15:40:29 +00:00
}
impl ApiError {
2023-12-03 09:49:10 +00:00
pub fn new_from_anyhow(status: StatusCode, error: anyhow::Error) -> Self {
2023-12-02 15:59:20 +00:00
Self {
status: Some(status),
2023-12-03 09:49:10 +00:00
kind: ApiErrorKind::Other(error),
2023-12-02 15:59:20 +00:00
plaintext: false,
}
}
2022-12-08 15:40:29 +00:00
pub const fn torrent_not_found(torrent_id: usize) -> Self {
Self {
status: Some(StatusCode::NOT_FOUND),
kind: ApiErrorKind::TorrentNotFound(torrent_id),
plaintext: false,
2022-12-08 15:40:29 +00:00
}
}
2022-12-08 20:58:23 +00:00
2023-11-25 00:24:32 +00:00
#[allow(dead_code)]
2023-11-24 18:28:46 +00:00
pub fn not_implemented(msg: &str) -> Self {
Self {
status: Some(StatusCode::INTERNAL_SERVER_ERROR),
kind: ApiErrorKind::Other(anyhow::anyhow!("{}", msg)),
plaintext: false,
}
}
2022-12-08 15:40:29 +00:00
pub const fn dht_disabled() -> Self {
Self {
status: Some(StatusCode::NOT_FOUND),
kind: ApiErrorKind::DhtDisabled,
plaintext: false,
2022-12-08 15:40:29 +00:00
}
}
2022-12-08 20:58:23 +00:00
pub fn status(&self) -> StatusCode {
self.status.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
}
2022-12-08 15:40:29 +00:00
pub fn with_status(self, status: StatusCode) -> Self {
Self {
status: Some(status),
kind: self.kind,
plaintext: self.plaintext,
}
}
pub fn with_plaintext_error(self, value: bool) -> Self {
Self {
status: self.status,
kind: self.kind,
plaintext: value,
2022-12-08 15:40:29 +00:00
}
}
}
#[derive(Debug)]
enum ApiErrorKind {
TorrentNotFound(usize),
DhtDisabled,
Other(anyhow::Error),
}
2022-12-08 20:43:02 +00:00
impl Serialize for ApiError {
2022-12-08 20:13:01 +00:00
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
2022-12-08 20:43:02 +00:00
#[derive(Serialize, Default)]
struct SerializedError<'a> {
error_kind: &'a str,
human_readable: String,
status: u16,
status_text: String,
2022-12-08 20:43:02 +00:00
#[serde(skip_serializing_if = "Option::is_none")]
id: Option<usize>,
2022-12-08 20:13:01 +00:00
}
2022-12-08 20:43:02 +00:00
let mut serr: SerializedError = SerializedError {
error_kind: match self.kind {
ApiErrorKind::TorrentNotFound(_) => "torrent_not_found",
ApiErrorKind::DhtDisabled => "dht_disabled",
ApiErrorKind::Other(_) => "internal_error",
},
human_readable: format!("{self}"),
2022-12-08 20:58:23 +00:00
status: self.status().as_u16(),
status_text: self.status().to_string(),
2022-12-08 20:43:02 +00:00
..Default::default()
};
2022-12-08 21:10:34 +00:00
if let ApiErrorKind::TorrentNotFound(id) = &self.kind {
serr.id = Some(*id)
2022-12-08 20:43:02 +00:00
}
serr.serialize(serializer)
2022-12-08 20:13:01 +00:00
}
}
2022-12-08 15:40:29 +00:00
impl From<anyhow::Error> for ApiError {
fn from(value: anyhow::Error) -> Self {
2022-12-08 21:10:34 +00:00
let status = value.downcast_ref::<ApiError>().and_then(|e| e.status);
2022-12-08 15:40:29 +00:00
Self {
2022-12-08 21:10:34 +00:00
status,
2022-12-08 15:40:29 +00:00
kind: ApiErrorKind::Other(value),
plaintext: false,
2022-12-08 15:40:29 +00:00
}
}
}
impl std::error::Error for ApiError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ApiErrorKind::Other(err) => err.source(),
_ => None,
}
}
}
impl std::fmt::Display for ApiError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ApiErrorKind::TorrentNotFound(idx) => write!(f, "torrent {idx} not found"),
2023-12-01 11:28:35 +00:00
ApiErrorKind::Other(err) => write!(f, "{err:?}"),
2022-12-08 15:40:29 +00:00
ApiErrorKind::DhtDisabled => write!(f, "DHT is disabled"),
}
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
2022-12-08 20:43:02 +00:00
let mut response = axum::Json(&self).into_response();
2022-12-08 20:58:23 +00:00
*response.status_mut() = self.status();
2022-12-08 15:40:29 +00:00
response
}
}
pub trait ApiErrorExt<T> {
2022-12-08 15:40:29 +00:00
fn with_error_status_code(self, s: StatusCode) -> Result<T, ApiError>;
fn with_plaintext_error(self, value: bool) -> Result<T, ApiError>;
2022-12-08 15:40:29 +00:00
}
impl<T, E> ApiErrorExt<T> for std::result::Result<T, E>
2022-12-08 15:40:29 +00:00
where
E: Into<ApiError>,
{
fn with_error_status_code(self, s: StatusCode) -> Result<T, ApiError> {
self.map_err(|e| e.into().with_status(s))
}
fn with_plaintext_error(self, value: bool) -> Result<T, ApiError> {
self.map_err(|e| e.into().with_plaintext_error(value))
}
2022-12-08 15:40:29 +00:00
}