Home >Web Front-end >JS Tutorial >Logging System with Proxy and Fetch

Logging System with Proxy and Fetch

Patricia Arquette
Patricia ArquetteOriginal
2024-12-03 09:12:10527browse

Logging System with Proxy and Fetch

  1. Proxy Object: The fetchLogger wraps the fetch function.
    It uses the apply trap to intercept calls to fetch.

  2. Request Logging:Logs the url and options of the request.
    Response Handling: Logs the response status, status text, and URL.
    Clones the response to ensure the body can be read multiple times.

  3. Error Handling: Captures and logs any errors encountered during the fetch.

  4. Using the Proxy: You can replace fetch globally by assigning the proxy to window.fetch.

// Create a logging wrapper for fetch using Proxy
const fetchLogger = new Proxy(fetch, {
    apply: (target, thisArg, args) => {
        // Log the request details
        const [url, options] = args;
        console.log("Fetch Request:");
        console.log("URL:", url);
        console.log("Options:", options);

        // Call the original fetch function
        return Reflect.apply(target, thisArg, args)
            .then(response => {
                // Log response details
                console.log("Fetch Response:");
                console.log("Status:", response.status);
                console.log("Status Text:", response.statusText);
                console.log("URL:", response.url);

                // Return the response for further use
                return response.clone(); // Clone to allow response reuse
            })
            .catch(error => {
                // Log errors
                console.error("Fetch Error:", error);
                throw error; // Rethrow the error for caller handling
            });
    }
});

// Example usage of the logging fetch
fetchLogger("https://jsonplaceholder.typicode.com/posts", {
    method: "GET",
    headers: {
        "Content-Type": "application/json"
    }
})
    .then(response => response.json())
    .then(data => console.log("Data:", data))
    .catch(error => console.error("Error in fetch:", error));

Replace Global fetch with Logging

window.fetch = fetchLogger;

The above is the detailed content of Logging System with Proxy and Fetch. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn