How can I specifically use `console.log` to track errors and exceptions within a Cloudflare Worker?

Responsive Ad Header

Question

Grade: Education Subject: Support
How can I specifically use `console.log` to track errors and exceptions within a Cloudflare Worker?
Asked by:
99 Viewed 99 Answers
Responsive Ad After Question

Answer (99)

Best Answer
(511)
To track errors, wrap your Worker logic that might throw an error in a `try...catch` block. Within the `catch` block, use `console.error()` (which specifically flags logs as errors) or `console.log()` to output details about the exception. For example: `try { // ... worker logic ... } catch (error) { console.error('An unhandled error occurred:', error.message, error.stack); event.respondWith(new Response('Internal Server Error', { status: 500 })); }`. This makes error messages stand out in your log viewer.