pub enum Error {
WebSocket(Error),
Io(Error),
Json(Error),
ConnectionNotFound(String),
RouteNotFound(String),
InvalidMessage,
Handler(String),
Extractor(String),
Custom(String),
}Expand description
The main error type for WsForge operations.
This enum represents all possible errors that can occur in the WsForge framework.
It uses the thiserror crate to automatically
implement std::error::Error and provide good error messages.
§Variants
Each variant represents a specific category of error:
WebSocket: WebSocket protocol errors from tungsteniteIo: I/O errors from file operations or networkJson: JSON serialization/deserialization errorsConnectionNotFound: Connection lookup failuresRouteNotFound: Message routing failuresInvalidMessage: Malformed message formatHandler: Handler execution errorsExtractor: Type extraction errorsCustom: Application-defined errors
§Examples
§Handling Specific Error Types
use wsforge::prelude::*;
match result {
Ok(_) => println!("Success"),
Err(Error::ConnectionNotFound(id)) => {
println!("Connection {} not found - may have disconnected", id);
}
Err(Error::Json(e)) => {
println!("Failed to parse JSON: {}", e);
}
Err(e) => {
println!("Unexpected error: {}", e);
}
}§Error Propagation with ?
use wsforge::prelude::*;
async fn process_message(msg: Message) -> Result<String> {
// JSON errors are automatically converted to Error::Json
let data: serde_json::Value = msg.json()?;
// Custom validation
let username = data["username"]
.as_str()
.ok_or_else(|| Error::custom("Missing username field"))?;
Ok(format!("Hello, {}", username))
}Variants§
WebSocket(Error)
WebSocket protocol error.
This variant wraps errors from the tokio-tungstenite crate,
which include protocol violations, connection issues, and
framing errors.
§Examples
use wsforge::prelude::*;
let error = Error::from(err);
match error {
Error::WebSocket(e) => println!("WebSocket error: {}", e),
_ => {}
}Io(Error)
I/O error.
This variant wraps standard I/O errors that can occur during file operations, network operations, or other system-level operations.
§Examples
use wsforge::prelude::*;
use std::io;
let error = Error::from(io_err);
match error {
Error::Io(e) => println!("I/O error: {}", e),
_ => {}
}Json(Error)
JSON serialization or deserialization error.
This variant wraps errors from serde_json, which can occur when:
- Parsing invalid JSON
- Serializing data with unsupported types
- Missing required fields during deserialization
§Examples
use wsforge::prelude::*;
use serde::Deserialize;
#[derive(Deserialize)]
struct User {
id: u32,
name: String,
}
async fn parse_user(msg: Message) -> Result<User> {
// If JSON is invalid or missing fields, Error::Json is returned
let user: User = msg.json()?;
Ok(user)
}ConnectionNotFound(String)
Connection not found error.
This error occurs when attempting to send a message to a connection that no longer exists (usually because the client disconnected).
The variant contains the ID of the connection that couldn’t be found.
§Examples
use wsforge::prelude::*;
async fn send_notification(
manager: &ConnectionManager,
user_id: &str,
msg: &str,
) -> Result<()> {
let conn = manager
.get(&user_id.to_string())
.ok_or_else(|| Error::ConnectionNotFound(user_id.to_string()))?;
conn.send_text(msg)?;
Ok(())
}RouteNotFound(String)
Route not found error.
This error occurs when a message is sent to a route that doesn’t have a registered handler.
The variant contains the route path that couldn’t be found.
§Examples
use wsforge::prelude::*;
let route = "/unknown/path";
let error = Error::RouteNotFound(route.to_string());
println!("{}", error); // "Route not found: /unknown/path"InvalidMessage
Invalid message format error.
This error occurs when a message has an unexpected format or structure that the handler cannot process.
§Examples
use wsforge::prelude::*;
async fn validate_message(msg: &Message) -> Result<()> {
if msg.is_binary() {
return Err(Error::InvalidMessage);
}
let text = msg.as_text()
.ok_or(Error::InvalidMessage)?;
if text.is_empty() {
return Err(Error::InvalidMessage);
}
Ok(())
}Handler(String)
Handler execution error.
This error occurs when a message handler encounters an error during execution. The variant contains a description of what went wrong.
§Examples
use wsforge::prelude::*;
async fn process_command(cmd: &str) -> Result<()> {
match cmd {
"start" => Ok(()),
"stop" => Ok(()),
unknown => Err(Error::handler(
format!("Unknown command: {}", unknown)
)),
}
}Extractor(String)
Type extractor error.
This error occurs when a type extractor fails to extract data from the message or connection context. Common causes include:
- Missing required data in state
- Type mismatches
- Missing path or query parameters
§Examples
use wsforge::prelude::*;
async fn get_user_state(state: &AppState) -> Result<String> {
state
.get::<String>()
.ok_or_else(|| Error::extractor("User state not found"))
.map(|arc| (*arc).clone())
}Custom(String)
Custom application-defined error.
This variant allows applications to create custom errors with arbitrary messages. Use this for application-specific error conditions that don’t fit other categories.
§Examples
use wsforge::prelude::*;
async fn check_rate_limit(user_id: &str) -> Result<()> {
let request_count = get_request_count(user_id);
if request_count > 100 {
return Err(Error::custom(
format!("Rate limit exceeded for user {}", user_id)
));
}
Ok(())
}
Implementations§
Source§impl Error
impl Error
Sourcepub fn custom<T: Display>(msg: T) -> Self
pub fn custom<T: Display>(msg: T) -> Self
Creates a custom error with the given message.
This is a convenience method for creating Error::Custom variants.
Use this for application-specific errors that don’t fit into other
error categories.
§Arguments
msg- Any type that implementsDisplay(like&str,String, etc.)
§Examples
§With String Literals
use wsforge::prelude::*;
if some_condition() {
return Err(Error::custom("Something went wrong"));
}
Ok(())§With Formatted Strings
use wsforge::prelude::*;
let age = get_user_age(user_id);
if age > max_age {
return Err(Error::custom(
format!("User {} age {} exceeds maximum {}", user_id, age, max_age)
));
}
Ok(())Sourcepub fn handler<T: Display>(msg: T) -> Self
pub fn handler<T: Display>(msg: T) -> Self
Creates a handler error with the given message.
This is a convenience method for creating Error::Handler variants.
Use this for errors that occur during handler execution.
§Arguments
msg- Any type that implementsDisplay
§Examples
§Validation Errors
use wsforge::prelude::*;
async fn validate_input(data: &str) -> Result<()> {
if data.is_empty() {
return Err(Error::handler("Input cannot be empty"));
}
if data.len() > 1000 {
return Err(Error::handler(
format!("Input too long: {} characters (max 1000)", data.len())
));
}
Ok(())
}§Command Processing Errors
use wsforge::prelude::*;
async fn execute_command(cmd: &str, args: &[&str]) -> Result<String> {
match cmd {
"echo" if args.is_empty() => {
Err(Error::handler("echo command requires arguments"))
}
"echo" => Ok(args.join(" ")),
unknown => Err(Error::handler(
format!("Unknown command: {}", unknown)
)),
}
}Sourcepub fn extractor<T: Display>(msg: T) -> Self
pub fn extractor<T: Display>(msg: T) -> Self
Creates an extractor error with the given message.
This is a convenience method for creating Error::Extractor variants.
Use this when type extraction fails, such as when required data is
missing from the request context.
§Arguments
msg- Any type that implementsDisplay
§Examples
§Missing State Data
use wsforge::prelude::*;
use std::sync::Arc;
struct DatabasePool;
async fn get_database(state: &AppState) -> Result<Arc<DatabasePool>> {
state
.get::<DatabasePool>()
.ok_or_else(|| Error::extractor("Database pool not found in state"))
}§Missing Path Parameters
use wsforge::prelude::*;
async fn extract_user_id(extensions: &Extensions) -> Result<u32> {
extensions
.get::<u32>("user_id")
.map(|arc| *arc)
.ok_or_else(|| Error::extractor("User ID not found in path"))
}§Type Mismatch
use wsforge::prelude::*;
async fn parse_count(value: &str) -> Result<usize> {
value.parse::<usize>().map_err(|_| {
Error::extractor(format!(
"Failed to parse '{}' as count (expected positive integer)",
value
))
})
}