Skip to main content

vpn_link_serde/
error.rs

1//! Error types for protocol parsing and serialization
2//!
3//! This crate uses a unified error convention (see crate-level docs):
4//! - **InvalidFormat**: Malformed link (e.g. missing `@` or `:` in main part, wrong structure).
5//! - **InvalidField**: Invalid or missing required field (e.g. port not in 1–65535, invalid u16).
6//! - **UnsupportedProtocol**: Unknown or unsupported scheme (e.g. `unknown://`).
7//! - **Base64DecodeError** / **JsonParseError** / **UrlParseError**: Decoding or parsing failures.
8
9use std::fmt;
10
11/// Result type for protocol parsing operations
12pub type Result<T> = std::result::Result<T, ProtocolError>;
13
14/// Errors that can occur during protocol parsing and serialization
15#[derive(Debug, Clone, PartialEq)]
16pub enum ProtocolError {
17    /// Invalid link format (e.g. missing `@` or `:` in main part)
18    InvalidFormat(String),
19    /// Unsupported or unknown protocol scheme
20    UnsupportedProtocol(String),
21    /// Base64 decoding error
22    Base64DecodeError(String),
23    /// JSON parsing error (e.g. VMess V2 body)
24    JsonParseError(String),
25    /// URL parsing or decoding error (e.g. fragment, query)
26    UrlParseError(String),
27    /// Missing required field
28    MissingField(String),
29    /// Invalid field value (e.g. port out of range)
30    InvalidField(String),
31    /// IO error
32    IoError(String),
33}
34
35impl fmt::Display for ProtocolError {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            ProtocolError::InvalidFormat(msg) => write!(f, "Invalid format: {}", msg),
39            ProtocolError::UnsupportedProtocol(msg) => write!(f, "Unsupported protocol: {}", msg),
40            ProtocolError::Base64DecodeError(msg) => write!(f, "Base64 decode error: {}", msg),
41            ProtocolError::JsonParseError(msg) => write!(f, "JSON parse error: {}", msg),
42            ProtocolError::UrlParseError(msg) => write!(f, "URL parse error: {}", msg),
43            ProtocolError::MissingField(msg) => write!(f, "Missing required field: {}", msg),
44            ProtocolError::InvalidField(msg) => write!(f, "Invalid field value: {}", msg),
45            ProtocolError::IoError(msg) => write!(f, "IO error: {}", msg),
46        }
47    }
48}
49
50impl std::error::Error for ProtocolError {}
51
52impl From<base64::DecodeError> for ProtocolError {
53    fn from(err: base64::DecodeError) -> Self {
54        ProtocolError::Base64DecodeError(err.to_string())
55    }
56}
57
58impl From<serde_json::Error> for ProtocolError {
59    fn from(err: serde_json::Error) -> Self {
60        ProtocolError::JsonParseError(err.to_string())
61    }
62}
63
64impl From<std::num::ParseIntError> for ProtocolError {
65    fn from(err: std::num::ParseIntError) -> Self {
66        ProtocolError::InvalidField(format!("Parse integer error: {}", err))
67    }
68}