User Agents

Web browsers and everyday web tech, explained

How to Read Browser and Page Errors in Puppeteer Sharp

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Reading browser and page errors in Puppeteer Sharp is essential for debugging automation scripts. This guide shows you how to capture console messages, page errors, request failures, and browser-level diagnostics so you can quickly identify and fix issues in your C# automation projects.

What You'll Need

  • A C# project with the PuppeteerSharp NuGet package installed (version 2.0.0 or later recommended).
  • Basic familiarity with async/await in C#.
  • An internet connection to download the browser if not already cached.

Step-by-Step

  1. Create a browser instance and a page.
    Start by launching the browser and opening a new page. Use await Browser.NewPageAsync(). This gives you a Page object where most events are hooked.
  2. Subscribe to the Page.Console event.
    This event fires for any console.log, console.warn, console.error, or other console calls from the page. The event handler receives a ConsoleEventArgs containing a Message object. Access the text via e.Message.Text and the type via e.Message.Type. Example:
    page.Console += (sender, e) => Console.WriteLine($"[Console] {e.Message.Type}: {e.Message.Text}");
  3. Listen to the Page.PageError event.
    This fires when an uncaught JavaScript exception occurs on the page. The event args contain the error message. Example:
    page.PageError += (sender, e) => Console.WriteLine($"[PageError] {e.Message}");
  4. Capture request failures.
    The Page.RequestFailed event fires when a network request fails (e.g., 404, DNS error, timeout). The args contain the request URL and the failure error text. Example:
    page.RequestFailed += (sender, e) => Console.WriteLine($"[RequestFailed] {e.Request.Url} - {e.FailureText}");
  5. Handle Page.Response for HTTP errors.
    To catch non-2xx responses, subscribe to Page.Response and check e.Response.Status. Example:
    page.Response += (sender, e) => { if ((int)e.Response.Status >= 400) Console.WriteLine($"[HTTP] {e.Response.Status} {e.Response.Url}"); };
  6. Enable browser-level logging.
    Pass --enable-logging and --v=1 to the browser launch options to get verbose output from the browser process. This is useful for crashes or network issues. Example:
    var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Args = new[] { "--enable-logging", "--v=1" } });
    The logs appear in the standard output (or debug output in Visual Studio).
  7. Use page.EvaluateFunctionAsync to catch errors in custom scripts.
    If you run custom JavaScript, wrap it in a try-catch and return the error message. Example:
    var result = await page.EvaluateFunctionAsync(@"() => { try { /* code */ } catch (e) { return e.message; } }");
  8. Combine all events in a helper method for reuse.
    Create a method that attaches all listeners to a page and logs to a file or console. This keeps your code clean and ensures you don't miss any error source.

Common Mistakes

  • Not attaching event handlers before navigation. If you attach after Page.GoToAsync, you might miss early errors. Attach immediately after creating the page.
  • Assuming PageError catches all JavaScript errors. It only catches uncaught exceptions. Errors caught by try-catch in the page will not trigger it; use Console for those.
  • Ignoring the Message.Type property. You might want to filter only errors, but logging everything helps in debugging. Don't discard warnings or info messages.
  • Forgetting to await DisposeAsync on the browser. This can cause the process to hang or not flush logs. Always dispose properly.

Tips

  • Log timestamps with each event to correlate errors with page actions.
  • Use structured logging (e.g., Serilog) to capture event data as JSON for easier analysis.
  • For intermittent errors, add a small delay before navigation to ensure all listeners are active.
  • When debugging network issues, also listen to Page.Request to see the request headers and body if needed.
  • Remember that PageError and Console events are async; if you need to do async work in the handler, use async void with a try-catch, but be careful with exceptions.

Troubleshooting

  • No events fire at all. Check that you are attaching handlers to the correct Page instance. If you create multiple pages, ensure you attach to the one you navigate. Also verify that the page is not a blank page (about:blank) before navigation.
  • Only some errors appear. Some errors, like resource loading failures, may be reported as RequestFailed but not as PageError. Make sure you have both handlers.
  • Browser logs are not showing. In Visual Studio, check the Output window (Debug) or the console if running from command line. The logs might be buffered; try adding --log-level=0 to force flushing.
  • Exceptions in event handlers. If your event handler throws, it can prevent subsequent events. Wrap handler bodies in try-catch and log any exceptions.
  • Errors occur before you attach handlers. If you navigate immediately after creating the page, errors during initial load may be missed. Use await page.WaitForNavigationAsync() after attaching handlers, or set Page.GoToAsync with WaitUntil: NavigationEvent.Load and attach before calling it.

Frequently Asked Questions

How do I get the stack trace of a page error?

The PageError event only provides the error message, not the stack trace. To get a stack trace, you can override window.onerror in the page to capture the stack and send it via console. Example: await page.EvaluateExpressionAsync("window.onerror = function(msg, url, line, col, error) { console.log(error.stack); }");

Can I capture errors from iframes?

Yes, the Page.Console and Page.PageError events fire for errors in iframes as well, as long as they are same-origin. For cross-origin iframes, you may need to attach listeners to the frame's page using Page.FrameManager or by using page.Frames and creating a new Page for each frame.

What is the difference between PageError and Console with type error?

PageError fires only for uncaught exceptions. Console with type error fires when the page explicitly calls console.error(). They are not mutually exclusive; an uncaught exception may also be logged to console by the browser.

How can I capture errors during PDF generation or screenshot?

Those operations are asynchronous and may not trigger page events. You can wrap them in try-catch in C# and also check the PageError event for any JavaScript errors that occur during the operation. For PDF, also check the Page.PrintToPDFAsync result for errors.

Is there a way to get all network requests that return 404?

Yes, use the Page.Response event and filter for status 404. You can also use Page.RequestFailed for network-level failures like DNS errors.

Can I use these events in headless mode?

Yes, all events work in headless mode. The browser logs may be less verbose, but the page events are identical.