ESP32 WebServer Library –  responseCodeToString()

Home / References / ESP32 Library / WebServer Library

Description

The responseCodeToString() method is a static utility function used to convert HTTP response status codes to their corresponding descriptive string representations. This method takes an integer HTTP status code and returns a human-readable string that describes the meaning of that status code (e.g., 200 returns “OK”, 404 returns “Not Found”). It’s particularly useful for logging, debugging, error reporting, creating custom response messages, and building comprehensive HTTP status monitoring systems. The method supports all standard HTTP status codes from 1xx (informational) through 5xx (server error) series, making it an essential tool for HTTP response handling and user-friendly error reporting in web server applications.


Syntax and Usage

The responseCodeToString() method has a simple syntax as a static method:

  • Convert status code to string: String statusText = WebServer::responseCodeToString(code) – Returns the descriptive string for the given HTTP status code.

For practical applications and examples of this method, please consult the “Example Code” section on this page. This section provides comprehensive guidance to help you better understand and apply the method effectively.


Arguments

  • code (int) – The HTTP status code to convert to its string representation. Supports standard HTTP codes including 1xx (informational), 2xx (success), 3xx (redirection), 4xx (client error), and 5xx (server error) series.

This page is part of the Comprehensive Guide to the ESP32 Arduino Core Library, accessible on AvantMaker.com.


Return Value

The responseCodeToString() method returns a String containing the descriptive text for the HTTP status code. For recognized status codes, it returns the standard HTTP reason phrase (e.g., “OK” for 200, “Not Found” for 404). For unrecognized or unsupported status codes, it returns an empty string. The returned strings are stored in flash memory for efficient memory usage.


Example Code

HTTP Status Code Reference and Logging System

This example demonstrates how to use the responseCodeToString() method to create a comprehensive HTTP status code reference system with logging capabilities. The server provides an interactive interface to explore different HTTP status codes, their meanings, and demonstrates practical usage in error handling and response logging scenarios.

How to use this example: Upload this code to your ESP32 and replace the WiFi credentials. After connecting, access the main page at http://ESP32_IP/ to see the HTTP status code reference dashboard. Test different endpoints to see various status codes in action: http://ESP32_IP/test/success for 200 OK, http://ESP32_IP/test/redirect for 302 Found, http://ESP32_IP/test/notfound for 404 Not Found, and http://ESP32_IP/test/error for 500 Internal Server Error. The system logs all responses with their status codes and descriptions to the Serial monitor.

/*
 * Author: Avant Maker
 * Date: June 18, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use the responseCodeToString() method to
 * create a comprehensive HTTP status code reference system with logging
 * capabilities. The server provides an interactive interface to explore
 * different HTTP status codes, their meanings, and demonstrates practical
 * usage in error handling and response logging scenarios.
 *
 * How to use this example:
 * Upload this code to your ESP32 and replace the WiFi credentials.
 * After connecting, access the main page at http://ESP32_IP/ to see the
 * HTTP status code reference dashboard. Test different endpoints to see
 * various status codes in action: http://ESP32_IP/test/success for 200 OK,
 * http://ESP32_IP/test/redirect for 302 Found, http://ESP32_IP/test/notfound
 * for 404 Not Found, and http://ESP32_IP/test/error for 500 Internal Server Error.
 * The system logs all responses with their status codes and descriptions
 * to the Serial monitor.
 *
 * Code Source:
 * This example code is sourced from the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
 * For additional code examples and in-depth documentation related to
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/home/all-about-esp32-arduino-core-library/
 *
 * AvantMaker.com, your premier destination for all things
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
 * to empowering makers, learners, and enthusiasts with
 * the resources they need to bring their nnovative ideas to life.
 */

#include <WiFi.h>
#include <WebServer.h>

const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";

WebServer server(80);

// Status code logging statistics
struct StatusCodeStats {
  unsigned long totalRequests = 0;
  unsigned long successResponses = 0;      // 2xx
  unsigned long redirectResponses = 0;     // 3xx
  unsigned long clientErrorResponses = 0;  // 4xx
  unsigned long serverErrorResponses = 0;  // 5xx
  String lastStatusCode = "";
  String lastStatusText = "";
} stats;

// Function to log response with status code conversion
void logResponse(int statusCode, const String& endpoint) {
  String statusText = WebServer::responseCodeToString(statusCode);
  stats.totalRequests++;
  stats.lastStatusCode = String(statusCode);
  stats.lastStatusText = statusText;
  
  // Categorize response by status code range
  if (statusCode >= 200 && statusCode < 300) {
    stats.successResponses++;
  } else if (statusCode >= 300 && statusCode < 400) {
    stats.redirectResponses++;
  } else if (statusCode >= 400 && statusCode < 500) {
    stats.clientErrorResponses++;
  } else if (statusCode >= 500 && statusCode < 600) {
    stats.serverErrorResponses++;
  }
  
  // Log to Serial with status code conversion
  Serial.println("=== HTTP Response Log ===");
  Serial.println("Endpoint: " + endpoint);
  Serial.println("Status Code: " + String(statusCode));
  Serial.println("Status Text: " + (statusText.length() > 0 ? statusText : "Unknown Status"));
  Serial.println("Timestamp: " + String(millis()) + "ms");
  Serial.println("========================");
}

void handleRoot() {
  // Log this response
  logResponse(200, "/");
  
  String html = "<!DOCTYPE html><html><head>";
  html += "<title>ESP32 HTTP Status Code Reference</title>";
  html += "<meta name='viewport' content='width=device-width, initial-scale=1'>";
  html += "<style>";
  html += "body{font-family:Arial,sans-serif;margin:20px;background:#f5f7fa;}";
  html += ".container{max-width:1100px;margin:0 auto;background:white;padding:30px;border-radius:15px;box-shadow:0 8px 25px rgba(0,0,0,0.1);}";
  html += ".status-display{background:#e8f5e8;padding:25px;border-radius:10px;margin:20px 0;border-left:6px solid #28a745;}";
  html += ".stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:20px;margin:25px 0;}";
  html += ".stat-card{background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);color:white;padding:25px;border-radius:12px;text-align:center;}";
  html += ".stat-number{font-size:2.2em;font-weight:bold;margin-bottom:8px;}";
  html += ".stat-label{font-size:0.9em;opacity:0.9;}";
  html += ".code-reference{background:#f8f9fa;padding:25px;border-radius:10px;margin:20px 0;}";
  html += ".code-group{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:15px;margin:15px 0;}";
  html += ".code-item{background:#ffffff;padding:15px;border-radius:8px;border-left:4px solid #007bff;box-shadow:0 2px 8px rgba(0,0,0,0.1);}";
  html += ".code-num{font-weight:bold;color:#007bff;font-size:1.1em;}";
  html += ".code-desc{color:#666;margin-top:5px;font-size:0.9em;}";
  html += ".test-section{background:#fff3cd;padding:25px;border-radius:10px;margin:20px 0;border:1px solid #ffeaa7;}";
  html += ".btn{background:#007bff;color:white;padding:12px 20px;border:none;border-radius:6px;text-decoration:none;margin:8px;display:inline-block;transition:all 0.3s;}";
  html += ".btn:hover{background:#0056b3;transform:translateY(-2px);}";
  html += ".btn.success{background:#28a745;} .btn.success:hover{background:#1e7e34;}";
  html += ".btn.warning{background:#ffc107;color:#212529;} .btn.warning:hover{background:#e0a800;}";
  html += ".btn.danger{background:#dc3545;} .btn.danger:hover{background:#c82333;}";
  html += ".btn.info{background:#17a2b8;} .btn.info:hover{background:#138496;}";
  html += "</style></head><body>";
  
  html += "<div class='container'>";
  html += "<h1>📊 ESP32 HTTP Status Code Reference</h1>";
  html += "<p>This system demonstrates the <code>responseCodeToString()</code> method by providing a comprehensive HTTP status code reference with live examples.</p>";
  
  // Display current response status
  html += "<div class='status-display'>";
  html += "<h3>✅ Current Response Status</h3>";
  html += "<p><strong>Status Code:</strong> 200</p>";
  html += "<p><strong>Status Text:</strong> " + WebServer::responseCodeToString(200) + "</p>";
  html += "<p><strong>Last Response:</strong> " + stats.lastStatusCode + " - " + stats.lastStatusText + "</p>";
  html += "</div>";
  
  // Display statistics
  html += "<div class='stats-grid'>";
  html += "<div class='stat-card'><div class='stat-number'>" + String(stats.totalRequests) + "</div><div class='stat-label'>Total Requests</div></div>";
  html += "<div class='stat-card'><div class='stat-number'>" + String(stats.successResponses) + "</div><div class='stat-label'>Success (2xx)</div></div>";
  html += "<div class='stat-card'><div class='stat-number'>" + String(stats.redirectResponses) + "</div><div class='stat-label'>Redirects (3xx)</div></div>";
  html += "<div class='stat-card'><div class='stat-number'>" + String(stats.clientErrorResponses) + "</div><div class='stat-label'>Client Errors (4xx)</div></div>";
  html += "<div class='stat-card'><div class='stat-number'>" + String(stats.serverErrorResponses) + "</div><div class='stat-label'>Server Errors (5xx)</div></div>";
  html += "</div>";
  
  // HTTP Status Code Reference
  html += "<div class='code-reference'>";
  html += "<h3>📋 HTTP Status Code Reference</h3>";
  html += "<p>Common HTTP status codes supported by <code>responseCodeToString()</code>:</p>";
  
  // Success codes (2xx)
  html += "<h4>✅ Success Codes (2xx)</h4>";
  html += "<div class='code-group'>";
  html += "<div class='code-item'><div class='code-num'>200 - " + WebServer::responseCodeToString(200) + "</div><div class='code-desc'>Request succeeded</div></div>";
  html += "<div class='code-item'><div class='code-num'>201 - " + WebServer::responseCodeToString(201) + "</div><div class='code-desc'>Resource created successfully</div></div>";
  html += "<div class='code-item'><div class='code-num'>204 - " + WebServer::responseCodeToString(204) + "</div><div class='code-desc'>Success with no content</div></div>";
  html += "</div>";
  
  // Redirection codes (3xx)
  html += "<h4>🔄 Redirection Codes (3xx)</h4>";
  html += "<div class='code-group'>";
  html += "<div class='code-item'><div class='code-num'>301 - " + WebServer::responseCodeToString(301) + "</div><div class='code-desc'>Resource moved permanently</div></div>";
  html += "<div class='code-item'><div class='code-num'>302 - " + WebServer::responseCodeToString(302) + "</div><div class='code-desc'>Resource found elsewhere</div></div>";
  html += "<div class='code-item'><div class='code-num'>304 - " + WebServer::responseCodeToString(304) + "</div><div class='code-desc'>Resource not modified</div></div>";
  html += "</div>";
  
  // Client error codes (4xx)
  html += "<h4>❌ Client Error Codes (4xx)</h4>";
  html += "<div class='code-group'>";
  html += "<div class='code-item'><div class='code-num'>400 - " + WebServer::responseCodeToString(400) + "</div><div class='code-desc'>Invalid request format</div></div>";
  html += "<div class='code-item'><div class='code-num'>401 - " + WebServer::responseCodeToString(401) + "</div><div class='code-desc'>Authentication required</div></div>";
  html += "<div class='code-item'><div class='code-num'>403 - " + WebServer::responseCodeToString(403) + "</div><div class='code-desc'>Access denied</div></div>";
  html += "<div class='code-item'><div class='code-num'>404 - " + WebServer::responseCodeToString(404) + "</div><div class='code-desc'>Resource not found</div></div>";
  html += "</div>";
  
  // Server error codes (5xx)
  html += "<h4>🚨 Server Error Codes (5xx)</h4>";
  html += "<div class='code-group'>";
  html += "<div class='code-item'><div class='code-num'>500 - " + WebServer::responseCodeToString(500) + "</div><div class='code-desc'>Server encountered an error</div></div>";
  html += "<div class='code-item'><div class='code-num'>501 - " + WebServer::responseCodeToString(501) + "</div><div class='code-desc'>Feature not implemented</div></div>";
  html += "<div class='code-item'><div class='code-num'>503 - " + WebServer::responseCodeToString(503) + "</div><div class='code-desc'>Service temporarily unavailable</div></div>";
  html += "</div>";
  html += "</div>";
  
  // Test endpoints
  html += "<div class='test-section'>";
  html += "<h3>🧪 Test HTTP Status Codes</h3>";
  html += "<p>Click these endpoints to see different HTTP status codes and their string representations:</p>";
  html += "<a href='/test/success' class='btn success'>200 Success Test</a>";
  html += "<a href='/test/redirect' class='btn info'>302 Redirect Test</a>";
  html += "<a href='/test/notfound' class='btn warning'>404 Not Found Test</a>";
  html += "<a href='/test/error' class='btn danger'>500 Server Error Test</a>";
  html += "<a href='/stats/reset' class='btn'>Reset Statistics</a>";
  html += "</div>";
  
  // Usage information
  html += "<h3>📖 How It Works</h3>";
  html += "<ul>";
  html += "<li>The <code>responseCodeToString()</code> method converts numeric HTTP codes to descriptive text</li>";
  html += "<li>All responses are automatically logged with their status codes and descriptions</li>";
  html += "<li>Statistics track different types of HTTP responses by category</li>";
  html += "<li>The method returns an empty string for unsupported status codes</li>";
  html += "<li>Status code strings are stored in flash memory for efficiency</li>";
  html += "</ul>";
  
  html += "<h3>📊 System Information</h3>";
  html += "<p>Free Heap: " + String(ESP.getFreeHeap()) + " bytes | ";
  html += "Uptime: " + String(millis()/1000) + "s | ";
  html += "WiFi Signal: " + String(WiFi.RSSI()) + " dBm</p>";
  
  html += "</div></body></html>";
  
  server.send(200, "text/html", html);
}

void handleSuccess() {
  logResponse(200, "/test/success");
  
  String response = "Success Test Response\n\n";
  response += "Status Code: 200\n";
  response += "Status Text: " + WebServer::responseCodeToString(200) + "\n";
  response += "Description: This demonstrates a standard successful HTTP response.\n";
  response += "Timestamp: " + String(millis()) + "ms\n";
  
  server.send(200, "text/plain", response);
}

void handleRedirect() {
  logResponse(302, "/test/redirect");
  
  // Set Location header for redirect (though we'll send content for demonstration)
  server.sendHeader("Location", "http://" + WiFi.localIP().toString() + "/");
  
  String response = "Redirect Test Response\n\n";
  response += "Status Code: 302\n";
  response += "Status Text: " + WebServer::responseCodeToString(302) + "\n";
  response += "Description: This demonstrates an HTTP redirect response.\n";
  response += "Note: In a real redirect, you would be automatically redirected.\n";
  response += "Timestamp: " + String(millis()) + "ms\n";
  
  server.send(302, "text/plain", response);
}

void handleNotFound() {
  logResponse(404, "/test/notfound");
  
  String response = "Not Found Test Response\n\n";
  response += "Status Code: 404\n";
  response += "Status Text: " + WebServer::responseCodeToString(404) + "\n";
  response += "Description: This demonstrates a 'resource not found' HTTP response.\n";
  response += "Timestamp: " + String(millis()) + "ms\n";
  response += "\nThis is a simulated 404 error for demonstration purposes.\n";
  
  server.send(404, "text/plain", response);
}

void handleServerError() {
  logResponse(500, "/test/error");
  
  String response = "Server Error Test Response\n\n";
  response += "Status Code: 500\n";
  response += "Status Text: " + WebServer::responseCodeToString(500) + "\n";
  response += "Description: This demonstrates an internal server error HTTP response.\n";
  response += "Timestamp: " + String(millis()) + "ms\n";
  response += "\nThis is a simulated 500 error for demonstration purposes.\n";
  response += "In a real scenario, this would indicate a server malfunction.\n";
  
  server.send(500, "text/plain", response);
}

void handleResetStats() {
  // Don't count this in stats reset
  int currentCode = 200;
  
  // Reset statistics
  stats.totalRequests = 1; // Keep this request
  stats.successResponses = 1;
  stats.redirectResponses = 0;
  stats.clientErrorResponses = 0;
  stats.serverErrorResponses = 0;
  stats.lastStatusCode = String(currentCode);
  stats.lastStatusText = WebServer::responseCodeToString(currentCode);
  
  String response = "Statistics Reset Complete!\n\n";
  response += "Status Code: " + String(currentCode) + "\n";
  response += "Status Text: " + WebServer::responseCodeToString(currentCode) + "\n";
  response += "All statistics have been reset to zero.\n\n";
  response += "Go back to: http://" + WiFi.localIP().toString() + "\n";
  
  server.send(200, "text/plain", response);
  Serial.println("HTTP status code statistics reset");
}

// Custom 404 handler that demonstrates responseCodeToString usage
void handleNotFoundCustom() {
  logResponse(404, server.uri());
  
  String message = "Custom 404 Handler\n\n";
  message += "The requested URL '" + server.uri() + "' was not found.\n";
  message += "Status Code: 404\n";
  message += "Status Text: " + WebServer::responseCodeToString(404) + "\n";
  message += "Server: ESP32 Status Code Demo\n";
  message += "Timestamp: " + String(millis()) + "ms\n";
  
  server.send(404, "text/plain", message);
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting ESP32 HTTP Status Code Reference System...");
  
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  Serial.println("WiFi connected!");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  
  // Set up route handlers
  server.on("/", handleRoot);
  server.on("/test/success", handleSuccess);
  server.on("/test/redirect", handleRedirect);
  server.on("/test/notfound", handleNotFound);
  server.on("/test/error", handleServerError);
  server.on("/stats/reset", handleResetStats);
  
  // Set custom 404 handler
  server.onNotFound(handleNotFoundCustom);
  
  // Start server
  server.begin();
  Serial.println("HTTP server started");
  Serial.println("Status code reference available at: http://" + WiFi.localIP().toString());
  Serial.println("Monitor Serial output for detailed response logging");
  
  // Test responseCodeToString with various codes
  Serial.println("\n=== Testing responseCodeToString() Method ===");
  int testCodes[] = {200, 201, 301, 302, 404, 403, 500, 503, 999};
  int numCodes = sizeof(testCodes) / sizeof(testCodes[0]);
  
  for (int i = 0; i < numCodes; i++) {
    int code = testCodes[i];
    String description = WebServer::responseCodeToString(code);
    Serial.println("Code " + String(code) + ": " + (description.length() > 0 ? description : "Unknown"));
  }
  Serial.println("=============================================");
}

void loop() {
  server.handleClient();
  
  // Optional: Print periodic statistics
  static unsigned long lastPrint = 0;
  if (millis() - lastPrint > 60000) { // Every 60 seconds
    lastPrint = millis();
    if (stats.totalRequests > 0) {
      Serial.println("📊 HTTP Status Code Statistics:");
      Serial.println("  Total requests: " + String(stats.totalRequests));
      Serial.println("  Success (2xx): " + String(stats.successResponses));
      Serial.println("  Redirects (3xx): " + String(stats.redirectResponses));
      Serial.println("  Client errors (4xx): " + String(stats.clientErrorResponses));
      Serial.println("  Server errors (5xx): " + String(stats.serverErrorResponses));
      Serial.println("  Last response: " + stats.lastStatusCode + " - " + stats.lastStatusText);
    }
  }
}

For more ESP32 development resources and tutorials, visit the All About ESP32 Resources Hub on  AvantMaker.com

error: Content is protected !!