1use 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("Missing world id")]
25 MissingWorldId,
26
27 #[error("{0}")]
28 RequestFailed(String),
29
30 #[error("Service unavailable")]
31 ServiceUnavailable,
32
33 #[error(transparent)]
34 Reqwest(#[from] reqwest::Error),
35 #[error(transparent)]
36 Tungstenite(#[from] tokio_tungstenite::tungstenite::Error),
37 #[error(transparent)]
38 Unknown(#[from] anyhow::Error),
39 #[error(transparent)]
40 Url(#[from] url::ParseError),
41}
42
43impl Serialize for Error {
44 fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
45 where
46 S: Serializer,
47 {
48 serializer.serialize_str(self.to_string().as_str())
49 }
50}
51
52#[cfg(feature = "lua")]
53impl From<Error> for mlua::Error {
54 fn from(err: Error) -> Self {
55 mlua::ExternalError::into_lua_err(err)
56 }
57}
58
59fn display_failed_to_connect_websocket(message: Option<&str>) -> String {
60 message
61 .map(ToOwned::to_owned)
62 .unwrap_or_else(|| String::from("Failed to connect websocket"))
63}