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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1TryFrom models conversions that can fail, returning a Result instead of panicking or silently defaulting.
- 2A dedicated error type that implements Display and Error integrates cleanly with the wider Rust error ecosystem.
- 3Modeling a closed set of values as an enum lets the compiler enforce exhaustiveness and enables ergonomic helper methods.
Related explainers
typescript
import { Controller } from '@nestjs/common'; import { MessagePattern, Payload,
Manual RabbitMQ acks in a NestJS controller
microservices
message-queue
acknowledgement
Intermediate
8 steps
rust
use axum::{ extract::{Request, State}, http::{HeaderValue, StatusCode}, middleware::Next,
API version headers with Axum middleware
middleware
http-headers
versioning
Intermediate
8 steps
rust
use axum::{ extract::Path, http::StatusCode, routing::{get, post},
Building a REST resource in Axum
rest-api
routing
serialization
Intermediate
9 steps
rust
use chrono::NaiveDate; use serde::{Deserialize, Deserializer}; #[derive(Debug, Deserialize)]
Custom date parsing with serde in Rust
serde
deserialization
csv-parsing
Intermediate
7 steps
python
import uuid from pathlib import Path from fastapi import APIRouter, File, Form, HTTPException, UploadFile
Handling multipart file uploads in FastAPI
file-upload
validation
multipart-form
Intermediate
6 steps
rust
use axum::{extract::State, http::StatusCode, Json}; use serde::{Deserialize, Serialize}; use sqlx::PgPool; use uuid::Uuid;
An atomic money transfer handler in Axum
database-transactions
atomicity
error-handling
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/converting-http-codes-with-tryfrom-in-rust-explained-rust-41f9/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.