0
0
DenoDebug / FixBeginner · 4 min read

How to Handle Errors in Oak Framework in Deno

In Oak for Deno, handle errors by adding a middleware that wraps your request handling in a try-catch block and sets the response status and body accordingly. Use ctx.throw() to raise errors and catch them in your error middleware to respond gracefully.
🔍

Why This Happens

When you don't catch errors in Oak middleware or routes, the server crashes or returns a generic 500 error without a clear message. This happens because Oak expects you to handle errors explicitly to keep the app stable and provide meaningful responses.

typescript
import { Application } from "https://deno.land/x/oak@v12.5.0/mod.ts";

const app = new Application();

app.use((ctx) => {
  // This will throw an error but no catch is present
  throw new Error("Something went wrong!");
});

await app.listen({ port: 8000 });
Output
Unhandled Error: Error: Something went wrong! at ... Server crashes or returns 500 without custom message
🔧

The Fix

Wrap your middleware logic in a try-catch block inside an error-handling middleware placed before other middleware. Use ctx.throw() to create errors with status codes. This way, you catch errors, set proper status and messages, and keep the server running smoothly.

typescript
import { Application } from "https://deno.land/x/oak@v12.5.0/mod.ts";

const app = new Application();

// Error handling middleware
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.response.status = err.status || 500;
    ctx.response.body = { error: err.message };
    ctx.response.type = "application/json";
  }
});

// Example route that throws an error
app.use((ctx) => {
  ctx.throw(400, "Bad Request Example");
});

await app.listen({ port: 8000 });
Output
{"error":"Bad Request Example"}
🛡️

Prevention

Always add a global error-handling middleware at the top of your middleware stack to catch all errors. Use ctx.throw() to create errors with status codes instead of raw throw. Test your routes to ensure errors return meaningful messages and status codes. Consider logging errors for debugging.

⚠️

Related Errors

Common related errors include unhandled promise rejections in async middleware and forgetting to call await next() which can cause middleware to hang. Fix these by always using await next() and wrapping async code in try-catch.

Key Takeaways

Use a top-level error-handling middleware with try-catch to catch all errors in Oak.
Use ctx.throw(status, message) to create errors with HTTP status codes.
Always await next() in middleware to ensure proper flow and error catching.
Return meaningful JSON error responses to clients for better debugging.
Test error cases to confirm your error handling works as expected.