Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc(examples): add examples with custom error handling #304

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,8 @@ path = "examples/chaining.rs"

name = "form_data"
path = "examples/form_data/form_data.rs"

[[example]]

name = "error_handling"
path = "examples/error_handling.rs"
77 changes: 77 additions & 0 deletions examples/error_handling.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#[macro_use] extern crate nickel;

use nickel::{Nickel, Request, Response, MiddlewareResult, HttpRouter};
use nickel::status::StatusCode;
use std::{error,io, fmt};

#[derive(Debug)]
pub enum AppError {
Io(io::Error),
Custom(String)
}

impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
AppError::Custom(ref msg) => write!(f, "Custom error: {}", msg),
AppError::Io(ref err) => write!(f, "IO error: {}", err)
}
}
}

impl error::Error for AppError {
fn description(&self) -> &str {
match *self {
AppError::Custom(ref msg) => msg,
AppError::Io(ref err) => err.description()
}
}

fn cause(&self) -> Option<&error::Error> {
match *self {
AppError::Custom(_) => None,
AppError::Io(ref err) => Some(err)
}
}
}

impl<'a> From<&'a AppError> for StatusCode {
fn from(err: &AppError) -> StatusCode {
match *err {
AppError::Custom(_) => StatusCode::BadRequest,
AppError::Io(_) => StatusCode::InternalServerError
}
}
}

type AppResult<T> = Result<T,AppError>;

fn will_fail() -> AppResult<String> {
Err(AppError::Custom("uups".to_string()))
}

fn will_work() -> AppResult<String> {
Ok("foo".to_string())
}

fn foo_handler<'a, D>(_: &mut Request<D>, mut res: Response<'a,D>) -> MiddlewareResult<'a, D> {

let x: AppResult<String> = (||Ok({
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is actually a hack that I really like to be simplified

try!(will_fail());
try!(will_work())
}))();

match x {
Ok(s) => res.send(s),
Err(ref err) => {
res.set(StatusCode::from(err));
res.send(err.to_string())
}
}
}

fn main() {
let mut server = Nickel::new();
server.get("foo/", foo_handler);
server.listen("127.0.0.1:6767");
}