Skip to main content

nil_server_database/
error.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use crate::sql_types::game_id::GameId;
5use crate::sql_types::id::UserId;
6use crate::sql_types::player_id::PlayerId;
7use either::Either;
8use serde::Serialize;
9use serde::ser::Serializer;
10use std::convert::Infallible;
11use std::io;
12use std::result::Result as StdResult;
13use tokio::task::JoinError;
14
15pub use diesel::result::Error as DieselError;
16pub use nil_core::error::Error as CoreError;
17
18pub type Result<T, E = Error> = StdResult<T, E>;
19pub type AnyResult<T> = anyhow::Result<T>;
20
21#[derive(Debug, thiserror::Error)]
22pub enum Error {
23  #[error("Game not found")]
24  GameNotFound(GameId),
25
26  #[error("Invalid password")]
27  InvalidPassword,
28
29  #[error("Invalid username: \"{0}\"")]
30  InvalidUsername(PlayerId),
31
32  #[error("User already exists: \"{0}\"")]
33  UserAlreadyExists(PlayerId),
34
35  #[error("User not found")]
36  UserNotFound(Either<PlayerId, UserId>),
37
38  #[error(transparent)]
39  Core(#[from] CoreError),
40  #[error(transparent)]
41  Diesel(#[from] diesel::result::Error),
42  #[error(transparent)]
43  DieselConnection(#[from] diesel::ConnectionError),
44  #[error(transparent)]
45  Io(#[from] io::Error),
46  #[error(transparent)]
47  Jiff(#[from] jiff::Error),
48  #[error(transparent)]
49  Unknown(#[from] anyhow::Error),
50}
51
52impl Serialize for Error {
53  fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
54  where
55    S: Serializer,
56  {
57    serializer.serialize_str(self.to_string().as_str())
58  }
59}
60
61impl<E> From<Result<Infallible, E>> for Error
62where
63  E: Into<Error>,
64{
65  fn from(value: Result<Infallible, E>) -> Self {
66    value.unwrap_err().into()
67  }
68}
69
70impl From<JoinError> for Error {
71  fn from(err: JoinError) -> Self {
72    Self::Io(io::Error::from(err))
73  }
74}