ESP32 HTTPClient Library – errorToString

Home / References / ESP32 Library / HTTPClient

Description

The errorToString method is a utility function in the ESP32 HTTPClient Library that converts an HTTP error code (an integer) into a human-readable string. This method is invaluable for debugging and understanding issues that occur during HTTP requests, such as connection failures or invalid responses. By translating numeric error codes into descriptive messages, it helps developers quickly identify and resolve problems in their projects.


Syntax and Usage

The errorToString method is straightforward to use and is typically called after an HTTP request to interpret the result code. Below is the basic syntax:

String HTTPClient::errorToString(int error)

This method has only one way of usage:

  • Using the method with an error code argument: Pass an integer error code (usually obtained from an HTTP request like GET() or POST()) to receive a descriptive string explaining the error.

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.


Argument(s)

  • error (int): An integer representing the HTTP error code or status returned by an HTTP request. This could be a positive value (e.g., HTTP response codes like 404) or a negative value (e.g., library-specific error codes like -1 for connection refused).

Return Value

The method returns a String object containing a human-readable description of the error code. For example, an error code of -1 returns "HTTPC_ERROR_CONNECTION_REFUSED", while 404 returns "HTTP_CODE_NOT_FOUND". If the error code is not recognized, it may return an empty string or a generic message, depending on the library implementation.


Example Codes

Example1

Below is an example demonstrating how to use the errorToString method in a practical scenario. This example corresponds to the usage described in Section 2.

Example: Handling HTTP Request Errors

This code connects an ESP32 to WiFi and attempts to perform a GET request to www.httpbin.org. If an error occurs, it uses errorToString to print a readable error message to the Serial Monitor.

/*
 * Author: Avant Maker
 * Date: February 24, 2025
 * Version: 1.0
 * Description: This code connects an ESP32 to WiFi and attempts 
 * to perform a GET request to www.httpbin.org. If an error occurs,
 * it uses errorToString to print a readable error message
 * to the Serial Monitor.
 *
 * License: MIT 
 * 
 * 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/references/esp32-arduino-core-index/
 *
 * 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 innovative ideas to life.
 */

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "your-SSID";       // Replace with your WiFi SSID
const char* password = "your-PASSWORD"; // Replace with your WiFi password

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);

    // Wait for WiFi connection
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nConnected to WiFi");
}

void loop() {
    HTTPClient http;

    // Begin HTTP request to a test endpoint
    http.begin("http://www.httpbin.org/get");

    // Send GET request
    int httpCode = http.GET();

    // Check if the request was successful
    if (httpCode > 0) {
        Serial.printf("Request succeeded with code: %d\n", httpCode);
    } else {
        // Print error message using errorToString
        String errorMessage = http.errorToString(httpCode);
        Serial.printf("Request failed with error: %s\n", errorMessage.c_str());
    }

    // Clean up
    http.end();

    delay(5000); // Wait 5 seconds before the next request
}

Explanation: In this example, the ESP32 attempts a GET request to www.httpbin.org/get. The http.GET() method returns an integer httpCode. If the code is positive, it indicates a successful HTTP response (e.g., 200 for OK). If negative, it signifies an error (e.g., -1 for connection refused). The errorToString method converts this code into a readable string, which is printed to the Serial Monitor for debugging.

Example2

This ESP32 Arduino sketch demonstrates how to retrieve and display error messages associated with the HTTPClient library’s error codes. The program iterates through error codes from -1 to -11, converting each to its corresponding string representation using errorToString(). It then prints both the error code and a detailed explanation to the Serial Monitor.

This is useful for debugging HTTP connection issues when using the ESP32 to communicate with web servers. Common errors include connection refusal, timeout, insufficient memory, and stream-related failures.

/*
 * Author: Avant Maker
 * Date: February 24, 2025
 * Version: 1.0
 * Description: demonstrates how to retrieve and display 
 * error messages associated with the HTTPClient library's
 * error codes. The program iterates through error codes
 * from -1 to -11, converting each to its corresponding
 * string representation using errorToString.
 * It then prints both the error code and a detailed
 * explanation to the Serial Monitor.
 *
 * License: MIT 
 * 
 * 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/references/esp32-arduino-core-index/
 *
 * 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 innovative ideas to life.
 */

#include <WiFi.h>
#include <HTTPClient.h>

void setup() {
    Serial.begin(115200);
    delay(1000); // Give Serial Monitor time to initialize
    Serial.println("ESP32 HTTPClient Error Codes:");

    HTTPClient http; // Create an instance to access errorToString

    // Loop through error codes -1 to -11
    for (int errorCode = -1; errorCode >= -11; errorCode--) {
        String errorMessage = http.errorToString(errorCode);
        Serial.printf("%d (%s): ", errorCode, errorMessage.c_str());

        // Map error codes to their detailed descriptions
        switch (errorCode) {
            case -1:
                Serial.println("Connection to the server was refused.");
                break;
            case -2:
                Serial.println("Failed to send HTTP headers.");
                break;
            case -3:
                Serial.println("Failed to send payload (not typically applicable to GET).");
                break;
            case -4:
                Serial.println("Not connected to the server.");
                break;
            case -5:
                Serial.println("Connection to the server was lost.");
                break;
            case -6:
                Serial.println("No stream available to read the response.");
                break;
            case -7:
                Serial.println("Server did not respond as an HTTP server.");
                break;
            case -8:
                Serial.println("Insufficient RAM to complete the operation.");
                break;
            case -9:
                Serial.println("Transfer encoding error (e.g., unsupported chunked encoding).");
                break;
            case -10:
                Serial.println("Error writing to the stream.");
                break;
            case -11:
                Serial.println("Read operation timed out.");
                break;
            default:
                Serial.println("Unknown error.");
                break;
        }
    }

    // Clean up (not strictly necessary here, but good practice)
    http.end();
}

void loop() {
    // Empty loop, as we only need to run this once in setup
}
error: Content is protected !!