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(transparent)]
31 Reqwest(#[from] reqwest::Error),
32 #[error(transparent)]
33 Unknown(#[from] anyhow::Error),
34 #[error(transparent)]
35 Url(#[from] url::ParseError),
36}
37
38impl Serialize for Error {
39 fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
40 where
41 S: Serializer,
42 {
43 serializer.serialize_str(self.to_string().as_str())
44 }
45}
46
47#[cfg(feature = "lua")]
48impl From<Error> for mlua::Error {
49 fn from(err: Error) -> Self {
50 mlua::ExternalError::into_lua_err(err)
51 }
52}
53
54fn display_failed_to_connect_websocket(message: Option<&str>) -> String {
55 message
56 .map(ToOwned::to_owned)
57 .unwrap_or_else(|| String::from("Failed to connect websocket"))
58}