How it works...

In this recipe, we created a Rust project named nickel-errorhandling, which helps us spawn the web server using the nickel web application crate. By default, nickel catches all the errors with its default ErrorHandler and tries to take reasonable actions.

Starting at the top, we referenced the external nickel crate using the extern keyword and loaded all of its macros with #[macro_use].

We used the following units from the nickel crate:

  • The nickel crate is the application object and surface, which holds all the public APIs. It's a struct that implements all the fundamental methods for performing all the web application tasks.
  • NickelError is a basic error type for HTTP errors as well as user-defined errors.
  • Action is an enum data type provided by the nickel crate, where Continue and Halt are variants of the Action type.
  • Request is a container for all the request data.

We used nickel::status::StatusCode::NotFound; here, the status is a public module of the nickel crate, which defines the StatusCode enum type containing the different HTTP status codes. NotFound is one of them and std::io::Write, which is a trait that defines the write_all method, writes all the data in the entire buffer.

In the main function, we first assign server instances to a mutable variable and create a new nickel application object with Nickel::new(), which creates an instance of nickel with default error handling.

We create a custom error handler named custom_handler, which is invoked in the case of NotFound or 404 status code. We call the function, custom_404, which takes in two parameters, NickelError and Request, and returns an Action type. The custom_404 is a way to overwrite the default error handler to handle 404 cases with a custom view.

The custom_404 assigns the arguments &mut NickelError and &mut Request to err and _req, respectively. In the function, we assign err.stream, where stream is a field of the NickelError type to Some(ref mut res), and check whether it is true; else we return Continue(()). If true, we know that there has been an error when the end user tried to access the endpoint, and the next step is to check whether the status code res.status() is NotFound. In such a case, we write the custom 404 page with the res.write_all method and return Halt(()).

The server.handle_error registers an error handler, which will be invoked among other error handlers as soon as any regular handler returns an error; the other error handler in our case is custom_handler.

The server.listen method listens to the API requests on 127.0.0.1:6767 where it binds and listens for connections on the given host and port.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.104.95