How to Read Browser and Page Errors in Puppeteer Sharp
In this article
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
PuppeteerSharpNuGet 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
- Create a browser instance and a page.
Start by launching the browser and opening a new page. Useawait Browser.NewPageAsync(). This gives you aPageobject where most events are hooked. - Subscribe to the
Page.Consoleevent.
This event fires for anyconsole.log,console.warn,console.error, or other console calls from the page. The event handler receives aConsoleEventArgscontaining aMessageobject. Access the text viae.Message.Textand the type viae.Message.Type. Example:page.Console += (sender, e) => Console.WriteLine($"[Console] {e.Message.Type}: {e.Message.Text}"); - Listen to the
Page.PageErrorevent.
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}"); - Capture request failures.
ThePage.RequestFailedevent 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}"); - Handle
Page.Responsefor HTTP errors.
To catch non-2xx responses, subscribe toPage.Responseand checke.Response.Status. Example:page.Response += (sender, e) => { if ((int)e.Response.Status >= 400) Console.WriteLine($"[HTTP] {e.Response.Status} {e.Response.Url}"); }; - Enable browser-level logging.
Pass--enable-loggingand--v=1to 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). - Use
page.EvaluateFunctionAsyncto 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; } }"); - 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
PageErrorcatches all JavaScript errors. It only catches uncaught exceptions. Errors caught by try-catch in the page will not trigger it; useConsolefor those. - Ignoring the
Message.Typeproperty. You might want to filter only errors, but logging everything helps in debugging. Don't discard warnings or info messages. - Forgetting to await
DisposeAsyncon 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.Requestto see the request headers and body if needed. - Remember that
PageErrorandConsoleevents are async; if you need to do async work in the handler, useasync voidwith a try-catch, but be careful with exceptions.
Troubleshooting
- No events fire at all. Check that you are attaching handlers to the correct
Pageinstance. 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
RequestFailedbut not asPageError. 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=0to 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 setPage.GoToAsyncwithWaitUntil: NavigationEvent.Loadand 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.