Error

Enum Error 

Source
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:

§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

Source

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 implements Display (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(())
Source

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 implements Display
§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)
        )),
    }
}
Source

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 implements Display
§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
        ))
    })
}

Trait Implementations§

Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Error

Source§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Error

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<Error> for Error

Source§

fn from(source: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for Error

Source§

fn from(source: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for Error

Source§

fn from(source: Error) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !Freeze for Error

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more