Back to Blog
Lesson 35 of the Cloudflare: Cloudflare for Developers: DNS to CDN course
Cloud NativeAugust 13, 20264 min read

Error Handling and Alerts: A Guide for Developers

Learn to master Error Handling and Alerts in Cloudflare Workers. Implement middleware to catch failures, audit logs, and configure proactive notifications.

CloudflareWorkersReliabilityError HandlingMonitoringDevOps
Close-up of PHP code on a monitor, highlighting development and programming concepts.

Previously in this course, we explored Observability and Logging: Monitoring Cloudflare Workers Health to gain visibility into our application's behavior. While logging helps us inspect what happened after the fact, this lesson focuses on being proactive: we will implement error-handling middleware to intercept crashes before they reach your users and configure alerts to notify you the moment things go wrong.

The Philosophy of Resilient Workers

In serverless environments, unhandled exceptions are the enemy of reliability. Unlike a long-running server, a Worker instance might be ephemeral. If an error isn't caught, the request simply fails with a 500 error, leaving your user frustrated and you in the dark.

Robust Errors management requires a "catch-all" approach. By wrapping your request logic in middleware, you create a safety net that normalizes error responses, logs detailed diagnostics, and keeps your system predictable.

Implementing Global Error-Handling Middleware

Instead of writing try/catch blocks inside every single handler, we use a middleware pattern. This wraps your core logic, ensuring that any unhandled promise rejection or synchronous throw is caught at the top level.

Here is a standard pattern for a fetch handler with built-in error handling:

JAVASCRIPT
export default {
  async fetch(request, env, ctx) {
    try {
      // Your main application logic goes here
      return await handleRequest(request, env, ctx);
    } catch (err) {
      // Log the error internally
      console.error("Critical Failure:", err.stack);

      // Return a standardized, user-friendly JSON response
      return new Response(JSON.stringify({ 
        error: "Internal Server Error",
        requestId: request.headers.get("cf-ray") 
      }), {
        status: 500,
        headers: { "Content-Type": "application/json" }
      });
    }
  }
};

async function handleRequest(request, env, ctx) {
  // Simulate a potential failure
  throw new Error("Database connection timed out");
}

By returning the cf-ray ID in your error response, you provide a hook for users to report issues, which you can then cross-reference in your logs. This is similar to the principles discussed in Express Error Handling: Centralized Middleware for Node.js APIs, adapted for the edge.

Configuring Proactive Alerts

Logging is reactive; Alerts are proactive. In the Cloudflare dashboard, you can configure notifications to trigger when specific error thresholds are met.

  1. Navigate to Notifications in the Cloudflare dashboard.
  2. Select Add and choose the Worker Error trigger.
  3. Define your threshold (e.g., alert if the 5xx error rate exceeds 1% over a 5-minute window).
  4. Select your delivery method (Email, PagerDuty, or Webhook).

This setup ensures that you are notified of production regressions before your customers start opening support tickets.

Auditing Failure Logs

When an alert fires, you must audit your logs effectively. Don't just look for "error"; look for patterns. Use wrangler tail to stream logs in real-time or export them to R2/D1 for long-term storage.

If you find yourself frequently debugging identical stack traces, consider Interpreting Stack Traces: A Guide to Debugging Runtime Errors to understand the root cause rather than just patching the symptoms.

Hands-on Exercise

  1. Modify your project: Add the try/catch middleware pattern shown above to your primary worker.
  2. Inject a failure: Create a test route that intentionally throws an error.
  3. Verify: Deploy the worker, hit the route, and confirm that you receive a 500 JSON response with a cf-ray header instead of a raw browser error page.
  4. Alerting: Set up a test notification rule in the Cloudflare dashboard for "Worker Errors" and trigger it by hitting your faulty route repeatedly.

Common Pitfalls

  • Swallowing Errors: Never leave a catch block empty. If you catch an error, you must either log it or re-throw it. Silencing errors makes debugging nearly impossible.
  • Sensitive Data: Be careful not to leak database connection strings or environment secrets in your 500 error response. Always sanitize the err.message before sending it to the client.
  • Over-Alerting: Don't set alerts for every single 404. Focus your alerts on 5xx errors, which indicate internal application failures.

FAQ

Q: Should I use Sentry or similar tools for Workers? A: Yes. While Cloudflare provides logs, dedicated error tracking tools offer better grouping, alerting, and stack trace visualization.

Q: How do I handle asynchronous errors inside the middleware? A: Ensure your main handler is an async function and that you await all promises. Unhandled promise rejections can bypass simple try/catch blocks if not properly awaited.

Recap

We have moved from simple request handling to building resilient services. By implementing central error-handling middleware, we ensure our API remains predictable under duress. By configuring automated alerts, we ensure we are the first to know when the system fails, allowing us to maintain high Reliability standards.

Up next: We will begin our exploration of CI/CD by writing automated tests for our worker code.

Similar Posts