1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//! This module imports errors generated by `StaticDir` and which are provided as response to following Iron middlewares.

use std::error::Error;
use std::fmt;
use std::io;

use iron::status::Status;
use iron::prelude::IronError;

#[inline]
fn iron_err_by_err_code(err: io::Error) -> IronError {
    const NOT_A_DIR_STATUS_CODE: i32 = 20;

    match err.raw_os_error() {
        Some(NOT_A_DIR_STATUS_CODE) => IronError::new(err, Status::NotFound),
        _                           => IronError::new(err, Status::InternalServerError),
    }
}

/// Maps `std::io::Error` to `iron::prelude::IronError`. This function may be useful when dealing with IO errors while implementing custom `ResponseStrategy`.
#[inline]
pub fn io_to_iron(err: io::Error) -> IronError {
    match err.kind() {
        io::ErrorKind::NotFound         => IronError::new(err, Status::NotFound),
        io::ErrorKind::PermissionDenied => IronError::new(err, Status::Forbidden),
        io::ErrorKind::Other            => iron_err_by_err_code(err),
        _                               => IronError::new(err, Status::InternalServerError),
    }
}

/// Generated when failed to convert `OsString` to `String`
#[derive(Debug, PartialEq, Eq)]
pub struct BadString {
    desc: String,
}

impl BadString {
    pub fn new(desc: &str) -> BadString {
        BadString{ desc: desc.into() }
    }
}

impl Error for BadString {
    fn description(&self) -> &str { &self.desc }
}

impl fmt::Display for BadString {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.description())
    }
}