help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
rust-web-server
/
src
RSK World
rust-web-server
Rust Web Server - High-Performance Async Web Server + WebSocket Support + JWT Authentication + File Upload + Memory Safety + Educational Design
src
  • auth.rs15.7 KB
  • config.rs2.9 KB
  • error.rs5.2 KB
  • file_upload.rs19 KB
  • handlers.rs12.8 KB
  • lib.rs1.8 KB
  • main.rs6 KB
  • middleware.rs6.2 KB
  • static_files.rs9.9 KB
  • utils.rs9.6 KB
  • websocket.rs15.3 KB
error.rs
src/error.rs
Raw Download
Find: Go to:
/*
 * Error Handling Module - Rust Web Server
 * 
 * Created by RSK World (https://rskworld.in)
 * Founder: Molla Samser
 * Designer & Tester: Rima Khatun
 * 
 * Contact:
 * - Email: hello@rskworld.in, support@rskworld.in
 * - Phone: +91 93305 39277
 * - Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India, 713147
 * 
 * © 2026 RSK World. All rights reserved.
 * Content used for educational purposes only.
 */

use hyper::{Body, Response, StatusCode};
use std::fmt;
use thiserror::Error;

/// Custom error types for the web server
#[derive(Error, Debug)]
pub enum ServerError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("HTTP error: {0}")]
    Http(String),

    #[error("Parse error: {0}")]
    Parse(String),

    #[error("Configuration error: {0}")]
    Config(String),

    #[error("Static file error: {0}")]
    StaticFile(String),

    #[error("Not found: {0}")]
    NotFound(String),

    #[error("Internal server error: {0}")]
    Internal(String),

    #[error("Bad request: {0}")]
    BadRequest(String),

    #[error("Unauthorized: {0}")]
    Unauthorized(String),

    #[error("Forbidden: {0}")]
    Forbidden(String),

    #[error("Method not allowed: {0}")]
    MethodNotAllowed(String),

    #[error("Request timeout")]
    Timeout,

    #[error("Request entity too large")]
    PayloadTooLarge,
}

impl ServerError {
    /// Convert error to HTTP response
    pub fn to_response(&self) -> Response<Body> {
        let (status, message) = match self {
            ServerError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()),
            ServerError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
            ServerError::Unauthorized(msg) => (StatusCode::UNAUTHORIZED, msg.clone()),
            ServerError::Forbidden(msg) => (StatusCode::FORBIDDEN, msg.clone()),
            ServerError::MethodNotAllowed(msg) => (StatusCode::METHOD_NOT_ALLOWED, msg.clone()),
            ServerError::Timeout => (StatusCode::REQUEST_TIMEOUT, "Request timeout".to_string()),
            ServerError::PayloadTooLarge => (StatusCode::PAYLOAD_TOO_LARGE, "Request entity too large".to_string()),
            ServerError::Internal(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
            _ => (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error".to_string()),
        };

        Response::builder()
            .status(status)
            .header("content-type", "text/plain")
            .body(Body::from(message))
            .unwrap()
    }

    /// Get HTTP status code for the error
    pub fn status_code(&self) -> StatusCode {
        match self {
            ServerError::NotFound(_) => StatusCode::NOT_FOUND,
            ServerError::BadRequest(_) => StatusCode::BAD_REQUEST,
            ServerError::Unauthorized(_) => StatusCode::UNAUTHORIZED,
            ServerError::Forbidden(_) => StatusCode::FORBIDDEN,
            ServerError::MethodNotAllowed(_) => StatusCode::METHOD_NOT_ALLOWED,
            ServerError::Timeout => StatusCode::REQUEST_TIMEOUT,
            ServerError::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
            ServerError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

/// Result type alias for server operations
pub type ServerResult<T> = Result<T, ServerError>;

/// Error response builder
pub struct ErrorResponse {
    status: StatusCode,
    message: String,
    details: Option<String>,
}

impl ErrorResponse {
    pub fn new(status: StatusCode, message: impl Into<String>) -> Self {
        Self {
            status,
            message: message.into(),
            details: None,
        }
    }

    pub fn with_details(mut self, details: impl Into<String>) -> Self {
        self.details = Some(details.into());
        self
    }

    pub fn build(self) -> Response<Body> {
        let body = if let Some(details) = self.details {
            format!("{}\n\nDetails: {}", self.message, details)
        } else {
            self.message
        };

        Response::builder()
            .status(self.status)
            .header("content-type", "text/plain")
            .body(Body::from(body))
            .unwrap()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_response() {
        let error = ServerError::NotFound("Resource not found".to_string());
        let response = error.to_response();
        
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[test]
    fn test_error_status_code() {
        assert_eq!(ServerError::NotFound("test".to_string()).status_code(), StatusCode::NOT_FOUND);
        assert_eq!(ServerError::BadRequest("test".to_string()).status_code(), StatusCode::BAD_REQUEST);
        assert_eq!(ServerError::Internal("test".to_string()).status_code(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn test_error_response_builder() {
        let response = ErrorResponse::new(StatusCode::BAD_REQUEST, "Invalid input")
            .with_details("Missing required field")
            .build();
        
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }
}
169 lines•5.2 KB
rust

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer