Skip to main content

netcode/
error.rs

1use std::fmt;
2use std::io;
3
4use crate::{MAX_CLIENTS, MAX_PAYLOAD_BYTES, MAX_SERVERS_PER_CONNECT};
5
6/// Errors returned by this crate.
7#[derive(Debug)]
8#[non_exhaustive]
9pub enum Error {
10    /// A connect token failed to parse or contained an invalid field.
11    InvalidConnectToken,
12    /// AEAD encryption failed.
13    EncryptFailed,
14    /// AEAD decryption failed. The data was tampered with or the wrong key was used.
15    DecryptFailed,
16    /// A payload size was outside the range `[1, MAX_PAYLOAD_BYTES]`.
17    InvalidPayloadSize(usize),
18    /// The number of server addresses was outside the range `[1, MAX_SERVERS_PER_CONNECT]`,
19    /// or the public and internal address lists had different lengths.
20    InvalidServerAddresses,
21    /// The requested number of client slots was outside the range `[1, MAX_CLIENTS]`.
22    InvalidMaxClients(usize),
23    /// A socket operation failed.
24    Io(io::Error),
25}
26
27impl fmt::Display for Error {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match self {
30            Error::InvalidConnectToken => write!(f, "invalid connect token"),
31            Error::EncryptFailed => write!(f, "encryption failed"),
32            Error::DecryptFailed => write!(f, "decryption failed"),
33            Error::InvalidPayloadSize(size) => {
34                write!(f, "payload size {size} is out of range [1,{MAX_PAYLOAD_BYTES}]")
35            }
36            Error::InvalidServerAddresses => write!(
37                f,
38                "number of server addresses is out of range [1,{MAX_SERVERS_PER_CONNECT}] \
39                 or public and internal address lists differ in length"
40            ),
41            Error::InvalidMaxClients(n) => {
42                write!(f, "max clients {n} is out of range [1,{MAX_CLIENTS}]")
43            }
44            Error::Io(error) => write!(f, "socket error: {error}"),
45        }
46    }
47}
48
49impl std::error::Error for Error {
50    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51        match self {
52            Error::Io(error) => Some(error),
53            _ => None,
54        }
55    }
56}
57
58impl From<io::Error> for Error {
59    fn from(error: io::Error) -> Self {
60        Error::Io(error)
61    }
62}