DEV Community

Pratik sharma
Pratik sharma

Posted on

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));
Enter fullscreen mode Exit fullscreen mode

Replace Global fetch with Logging

window.fetch = fetchLogger;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)