Skip to content
Aurélien Brabant edited this page Nov 15, 2021 · 3 revisions

HTTP Status Code

HTTP status code are used to report success, errors, or other information such as redirect.

An abstraction for these codes is available inside the HTTP namespace: an enum is used to represent almost every HTTP status code by its name.

The toStatusCode function can be used to convert an unsigned integer to the corresponding status code, given that the passed number relates to a known status code.

Similarly, we can do it the other way around by using the second overload of toStatusCode, which returns an unsigned and takes an HTTP::StatusCode as its only parameter.

Example usage:

#include <iostream>
#include "http/status.hpp"

HTTP::StatusCode codeByEnum = HTTP::BAD_REQUEST; // <=> 400
HTTP::StatusCode codeByInteger = HTTP::toStatusCode(400); // <=> 400
unsigned intStatusCode = HTTP::toStatusCode(codeByInteger); // == 400

std::cout << std::boolalpha << (codeByEnum == codeByInteger) << std::endl;

This code will output true because these two status codes, although obtained differently, are the same.

String representation

Alternatively, it is possible to get a string that describes the status code (in case the status code exists) by using the HTTP::toStatusCodeString function:

std::cout << toStatusCodeString(200) << std::endl;

Would output "Request processed successfully".

If toStatusCodeString is passed an unknown status code, it will:

  • return the empty string ("") ONLY IF 100 <= statusCode <= 599
  • produce an undefined behavior (very likely going to be a segmentation fault) in case status code is out of the above range.

In short: never attempt to make a string from a status code that is less than 100 or greater than 599.

Clone this wiki locally