ESP32 WebServer Library – onNotFound()

Description

The onNotFound() method in the ESP32 WebServer Library is a powerful tool for handling HTTP requests that do not match any predefined routes in your web server. When a client attempts to access a URL that hasn’t been explicitly registered using methods like on(), this method triggers a custom callback function. It’s an essential feature for creating robust web servers, allowing you to define fallback behavior—such as returning a “404 Not Found” message or redirecting users—making it ideal for debugging or enhancing user experience in IoT projects.


Syntax and Usage

The onNotFound() method is straightforward to implement. It registers a callback function that executes when an unmatched request is received. Below is the syntax and its primary usage:

server.onNotFound(THandlerFunction fn);
  • Basic Usage with a Callback Function: Assign a function to handle all requests that don’t match any defined routes. This is typically used to send a custom error response or log the request details.

The method accepts a single argument—a function of type THandlerFunction—and does not support additional variations like HTTP method-specific handling (e.g., GET or POST), as it applies universally to all unmatched requests.

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)

  • fn (THandlerFunction): A callback function that defines the behavior when an unmatched route is requested. This function takes no parameters and returns no value (void). It provides access to the WebServer object (e.g., server) to process the request, such as sending a response using server.send().

Return Value

The onNotFound() method does not return a value. It is a void function designed solely to register the callback handler. The actual response to the client is managed within the callback function using methods like server.send().


Example Codes

Below is an example demonstrating the use of the onNotFound() method. This example sets up a simple web server and defines a custom response for unmatched routes.

Example: Handling 404 Errors with a Custom Message

This code creates a web server on an ESP32, connects to a Wi-Fi network, and uses onNotFound() to send a “404 Not Found” message for any undefined routes. Upload this sketch to your ESP32, connect to the specified Wi-Fi network, and open a browser to test the server’s IP address with an invalid path (e.g., http://[ESP32_IP]/unknown).

/*
 * Author: Avant Maker
 * Date: March 17, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use ESP32 WebServer Library's 
 * onNotFound() method to send a "404 Not Found" message for any 
 * undefined routes.
 *
 * 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 innovative ideas to life.
 */

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

// Replace with your network credentials
const char* ssid = "your-SSID";          // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD";  // Replace with your Wi-Fi password

WebServer server(80);

void setup() {
    Serial.begin(115200);

    // Connect to Wi-Fi
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("");
    Serial.print("Connected to WiFi. IP address: ");
    Serial.println(WiFi.localIP());

    // Define a basic route
    server.on("/", []() {
        server.send(200, "text/plain", "Welcome to the AvantMaker.com ESP32 Web Server!");
    });

    // Handle unmatched routes
    server.onNotFound([]() {
        server.send(404, "text/plain", "404: Page Not Found");
    });

    // Start the server
    server.begin();
    Serial.println("HTTP server started");
}

void loop() {
    server.handleClient();
}
error: Content is protected !!