
Building a Typed HTTP Status Code Helper in Rust
When you work with HTTP in Rust, status codes often appear as raw integers. That is fine for quick scripts, but in production code it can make intent harder to read and error handling easier to get wrong. A small typed abstraction can improve clarity, reduce magic numbers, and make response handling more expressive.
In this tutorial, you will build a compact, practical HTTP status code helper in Rust. The goal is not to replace existing web frameworks or HTTP clients, but to show how to model a narrow domain with strong types and clean APIs.
Why wrap HTTP status codes?
HTTP status codes are simple values, but they carry meaning. A 404 means “not found,” 201 means “created,” and 503 means “service unavailable.” If your code checks raw integers everywhere, the logic becomes harder to scan and maintain.
A typed helper gives you:
- clearer branching logic
- reusable classification methods
- safer comparisons
- a place to centralize common semantics
This is especially useful in service layers, API clients, middleware, and observability code where response handling is frequent.
What we are building
We will create a small StatusCode type that:
- stores the numeric code
- validates that it is within the HTTP range
- exposes common helpers like
is_success()andis_client_error() - provides named constructors for common codes
- supports conversion from and to
u16
This is intentionally lightweight. The design keeps the type easy to use while still improving correctness.
Core design
A good typed wrapper should be simple to adopt. In Rust, that usually means:
- a newtype around the primitive value
TryFrom<u16>for validationFrom<StatusCode> for u16for interoperability- methods for classification and common predicates
Here is the basic implementation.
use std::convert::TryFrom;
use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StatusCode(u16);
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StatusCodeError {
OutOfRange(u16),
}
impl fmt::Display for StatusCodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StatusCodeError::OutOfRange(code) => {
write!(f, "invalid HTTP status code: {}", code)
}
}
}
}
impl std::error::Error for StatusCodeError {}
impl StatusCode {
pub const fn as_u16(self) -> u16 {
self.0
}
pub const fn is_informational(self) -> bool {
self.0 >= 100 && self.0 < 200
}
pub const fn is_success(self) -> bool {
self.0 >= 200 && self.0 < 300
}
pub const fn is_redirection(self) -> bool {
self.0 >= 300 && self.0 < 400
}
pub const fn is_client_error(self) -> bool {
self.0 >= 400 && self.0 < 500
}
pub const fn is_server_error(self) -> bool {
self.0 >= 500 && self.0 < 600
}
pub const fn ok() -> Self {
Self(200)
}
pub const fn created() -> Self {
Self(201)
}
pub const fn bad_request() -> Self {
Self(400)
}
pub const fn not_found() -> Self {
Self(404)
}
pub const fn internal_server_error() -> Self {
Self(500)
}
}
impl TryFrom<u16> for StatusCode {
type Error = StatusCodeError;
fn try_from(value: u16) -> Result<Self, Self::Error> {
if (100..600).contains(&value) {
Ok(StatusCode(value))
} else {
Err(StatusCodeError::OutOfRange(value))
}
}
}
impl From<StatusCode> for u16 {
fn from(code: StatusCode) -> Self {
code.0
}
}
Using the helper in application code
The main advantage of this type is readability. Instead of comparing against raw numbers, you can write code that explains itself.
fn handle_response(code: StatusCode) -> &'static str {
if code.is_success() {
"request succeeded"
} else if code.is_client_error() {
"client error"
} else if code.is_server_error() {
"server error"
} else {
"other response"
}
}
fn main() {
let code = StatusCode::try_from(404).unwrap();
println!("{}", handle_response(code));
}
This is more maintainable than a chain of numeric comparisons because the intent is obvious at the call site.
Why TryFrom<u16> is the right boundary
Validation should happen at the edge of your system. HTTP status codes are often received from external sources such as:
- HTTP client libraries
- reverse proxies
- test fixtures
- logs and metrics pipelines
- mocked services
Using TryFrom<u16> makes invalid values impossible to ignore. If a caller tries to create 99 or 600, the conversion fails immediately.
That is better than storing invalid values and discovering them later in business logic.
Example: parsing from a configuration value
fn parse_status_code(raw: u16) -> Result<StatusCode, StatusCodeError> {
StatusCode::try_from(raw)
}
fn main() {
match parse_status_code(204) {
Ok(code) => println!("parsed status: {}", code.as_u16()),
Err(err) => eprintln!("error: {}", err),
}
}
Adding named constants for common codes
Named constructors are useful, but if you need a larger set of codes, associated constants can be even more ergonomic. They also work well in pattern-like comparisons.
| Category | Examples | Typical use |
|---|---|---|
| Informational | 100, 101 | protocol negotiation |
| Success | 200, 201, 204 | normal application flow |
| Redirection | 301, 302, 304 | routing and caching |
| Client error | 400, 401, 403, 404 | validation and authorization |
| Server error | 500, 502, 503 | operational failures |
You can extend the type with constants like this:
impl StatusCode {
pub const CONTINUE: Self = Self(100);
pub const OK: Self = Self(200);
pub const CREATED: Self = Self(201);
pub const NO_CONTENT: Self = Self(204);
pub const MOVED_PERMANENTLY: Self = Self(301);
pub const BAD_REQUEST: Self = Self(400);
pub const UNAUTHORIZED: Self = Self(401);
pub const FORBIDDEN: Self = Self(403);
pub const NOT_FOUND: Self = Self(404);
pub const INTERNAL_SERVER_ERROR: Self = Self(500);
pub const SERVICE_UNAVAILABLE: Self = Self(503);
}
This style is especially useful when you want a compact API and easy discoverability in IDE autocomplete.
Matching on typed status codes
Sometimes you need exact matches rather than broad classes. The wrapper still works well with match.
fn describe(code: StatusCode) -> &'static str {
match code {
c if c == StatusCode::OK => "success",
c if c == StatusCode::CREATED => "resource created",
c if c == StatusCode::NOT_FOUND => "missing resource",
c if c == StatusCode::SERVICE_UNAVAILABLE => "temporary outage",
_ if code.is_client_error() => "client-side failure",
_ if code.is_server_error() => "server-side failure",
_ => "unclassified response",
}
}
This pattern is useful when a few codes need special handling and the rest can be grouped by class.
Integrating with reqwest
A typed helper becomes more valuable when used alongside real HTTP clients. Suppose you are calling an API with reqwest and want to convert the response status into your own type.
use reqwest::blocking::Client;
fn fetch_status(url: &str) -> Result<StatusCode, Box<dyn std::error::Error>> {
let client = Client::new();
let response = client.get(url).send()?;
let raw = response.status().as_u16();
let status = StatusCode::try_from(raw)?;
Ok(status)
}
Now your application code can work with StatusCode instead of repeatedly handling raw integers. This is especially useful if you want to log, classify, or transform the result in a consistent way.
Best practices for this kind of type
A small wrapper can become noisy if it tries to do too much. Keep the API focused.
1. Validate at construction time
Do not allow invalid codes to exist inside the type. This keeps invariants strong and simplifies every method that follows.
2. Prefer Copy
A status code is tiny and immutable. Deriving Copy makes the type easy to pass around without ownership friction.
3. Keep classification methods const
Methods like is_success() and is_client_error() are pure checks. Marking them const makes the type more flexible and signals that they have no side effects.
4. Avoid over-modeling
You do not need a separate enum variant for every status code unless your application truly benefits from it. A numeric wrapper plus helpers is often the right balance.
5. Implement standard conversions
TryFrom<u16> and From<StatusCode> for u16 make the type easy to integrate with existing libraries and APIs.
Extending the helper for real projects
Once the basic wrapper is in place, you can extend it in ways that match your domain.
Add semantic helpers
For example:
impl StatusCode {
pub const fn is_error(self) -> bool {
self.is_client_error() || self.is_server_error()
}
pub const fn is_cacheable_by_default(self) -> bool {
matches!(self.0, 200 | 203 | 204 | 206 | 300 | 301 | 404 | 405 | 410 | 414 | 501)
}
}
This can be useful in proxy code, caching layers, or API gateways.
Add display formatting
If you want cleaner logs, implement Display:
impl fmt::Display for StatusCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
Then you can print the type directly without converting it first.
Add a richer error type
If your application needs to distinguish between different invalid inputs, expand StatusCodeError with more variants. For example, you might separate “out of range” from “non-standard but accepted” if your system has special rules.
When this pattern is a good fit
This approach works well when:
- you frequently inspect HTTP responses
- you want to reduce raw numeric comparisons
- you need a small, reusable domain type
- you are building libraries or shared internal crates
- you want validation at the boundary of your system
It is less useful if your code only checks a status code once in a simple script. In that case, the wrapper may be unnecessary ceremony.
Summary
A typed HTTP status code helper is a small but effective example of Rust’s strengths: explicit invariants, lightweight abstractions, and ergonomic conversions. By wrapping u16 in a validated type, you make response handling clearer and safer without adding much complexity.
The pattern scales well in real codebases because it improves readability at the exact points where HTTP semantics matter most: request handling, error classification, logging, and integration boundaries.