Skip to main content

nil_client/
error.rs

1// Copyright (C) Call of Nil contributors
2// SPDX-License-Identifier: AGPL-3.0-only
3
4use nil_core::player::PlayerId;
5use serde::Serialize;
6use serde::ser::Serializer;
7use std::result::Result as StdResult;
8
9#[doc(hidden)]
10pub type Result<T, E = Error> = StdResult<T, E>;
11#[doc(hidden)]
12pub type AnyResult<T> = anyhow::Result<T>;
13
14#[derive(Debug, thiserror::Error)]
15pub enum Error {
16  #[error("Failed to authenticate")]
17  FailedToAuthenticate,
18
19  #[error("{}", display_failed_to_connect_websocket(.0.as_deref()))]
20  FailedToConnectWebsocket(Option<String>),
21
22  #[error("Player name contains invalid characters: {0}")]
23  InvalidPlayerId(PlayerId),
24
25  #[error("Missing world id")]
26  MissingWorldId,
27
28  #[error("{0}")]
29  RequestFailed(String),
30
31  #[error("Service unavailable")]
32  ServiceUnavailable,
33
34  #[error(transparent)]
35  Reqwest(#[from] reqwest::Error),
36  #[error(transparent)]
37  Tungstenite(#[from] tokio_tungstenite::tungstenite::Error),
38  #[error(transparent)]
39  Unknown(#[from] anyhow::Error),
40  #[error(transparent)]
41  Url(#[from] url::ParseError),
42}
43
44impl Serialize for Error {
45  fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
46  where
47    S: Serializer,
48  {
49    serializer.serialize_str(self.to_string().as_str())
50  }
51}
52
53fn display_failed_to_connect_websocket(message: Option<&str>) -> String {
54  message
55    .map(ToOwned::to_owned)
56    .unwrap_or_else(|| String::from("Failed to connect websocket"))
57}