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;
7
8pub use std::result::Result as StdResult;
9
10pub type Result<T, E = Error> = StdResult<T, E>;
11pub type AnyResult<T> = anyhow::Result<T>;
12
13#[derive(Debug, thiserror::Error)]
14pub enum Error {
15  #[error("Failed to authenticate")]
16  FailedToAuthenticate,
17
18  #[error("{}", display_failed_to_connect_websocket(.0.as_deref()))]
19  FailedToConnectWebsocket(Option<String>),
20
21  #[error("Player name contains invalid characters: {0}")]
22  InvalidPlayerId(PlayerId),
23
24  #[error("{}", display_max_retries_exceeded(*.attempts, .message.as_deref()))]
25  MaxRetriesExceeded {
26    attempts: u8,
27    message: Option<String>,
28  },
29
30  #[error("Missing world id")]
31  MissingWorldId,
32
33  #[error("{0}")]
34  RequestFailed(String),
35
36  #[error("Service unavailable")]
37  ServiceUnavailable,
38
39  #[error(transparent)]
40  Reqwest(#[from] reqwest::Error),
41  #[error(transparent)]
42  Unknown(#[from] anyhow::Error),
43  #[error(transparent)]
44  Url(#[from] url::ParseError),
45}
46
47impl Serialize for Error {
48  fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
49  where
50    S: Serializer,
51  {
52    serializer.serialize_str(self.to_string().as_str())
53  }
54}
55
56#[cfg(feature = "lua")]
57impl From<Error> for mlua::Error {
58  fn from(err: Error) -> Self {
59    mlua::ExternalError::into_lua_err(err)
60  }
61}
62
63fn display_failed_to_connect_websocket(message: Option<&str>) -> String {
64  message
65    .map(ToOwned::to_owned)
66    .unwrap_or_else(|| String::from("Failed to connect websocket"))
67}
68
69fn display_max_retries_exceeded(attempts: u8, message: Option<&str>) -> String {
70  message
71    .map(ToOwned::to_owned)
72    .unwrap_or_else(|| format!("Request failed after {attempts} attempts"))
73}