rust 48 lines · 8 steps

Converting HTTP codes with TryFrom in Rust

A fallible conversion turns raw u16 status codes into a typed enum, with a custom error for anything unrecognized.

Explained by highlit
1use std::convert::TryFrom;
2 
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum HttpStatus {
5 Ok,
6 Created,
7 NoContent,
8 BadRequest,
9 Unauthorized,
10 Forbidden,
11 NotFound,
12 InternalServerError,
13}
14 
15#[derive(Debug, PartialEq, Eq)]
16pub struct InvalidStatus(u16);
17 
18impl std::fmt::Display for InvalidStatus {
19 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20 write!(f, "{} is not a supported HTTP status code", self.0)
21 }
22}
23 
24impl std::error::Error for InvalidStatus {}
25 
26impl TryFrom<u16> for HttpStatus {
27 type Error = InvalidStatus;
28 
29 fn try_from(value: u16) -> Result<Self, Self::Error> {
30 match value {
31 200 => Ok(HttpStatus::Ok),
32 201 => Ok(HttpStatus::Created),
33 204 => Ok(HttpStatus::NoContent),
34 400 => Ok(HttpStatus::BadRequest),
35 401 => Ok(HttpStatus::Unauthorized),
36 403 => Ok(HttpStatus::Forbidden),
37 404 => Ok(HttpStatus::NotFound),
38 500 => Ok(HttpStatus::InternalServerError),
39 other => Err(InvalidStatus(other)),
40 }
41 }
42}
43 
44impl HttpStatus {
45 pub fn is_success(self) -> bool {
46 matches!(self, HttpStatus::Ok | HttpStatus::Created | HttpStatus::NoContent)
47 }
48}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1TryFrom models conversions that can fail, returning a Result instead of panicking or silently defaulting.
  2. 2A dedicated error type that implements Display and Error integrates cleanly with the wider Rust error ecosystem.
  3. 3Modeling a closed set of values as an enum lets the compiler enforce exhaustiveness and enables ergonomic helper methods.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Converting HTTP codes with TryFrom in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code