Skip to content

Error Handling

BrewedSys edited this page Mar 30, 2026 · 1 revision

Error Handling

Http-native provides built-in error handling to catch and respond to errors gracefully.

Global Error Handler

Register a global error handler with app.error() or app.onError():

app.error(async (err, req, res) => {
  console.error(`Error on ${req.method} ${req.path}:`, err);
  res.status(err.statusCode || 500).json({
    error: err.message || "Internal server error",
  });
});
Argument Description
err The error object thrown or passed to next(err)
req The request object
res The response object

Throwing Errors in Handlers

Errors thrown in async handlers are automatically caught:

app.get("/users/:id", async (req, res) => {
  const user = await db.findUser(req.params.id);
  if (!user) {
    const error = new Error("User not found");
    error.statusCode = 404;
    throw error;
  }
  res.json(user);
});

Custom Error Classes

class AppError extends Error {
  constructor(message, statusCode = 500) {
    super(message);
    this.statusCode = statusCode;
  }
}

class NotFoundError extends AppError {
  constructor(resource = "Resource") {
    super(`${resource} not found`, 404);
  }
}

// Usage
app.get("/users/:id", async (req, res) => {
  const user = await db.findUser(req.params.id);
  if (!user) throw new NotFoundError("User");
  res.json(user);
});

// Error handler
app.error(async (err, req, res) => {
  const status = err.statusCode || 500;
  const body = { error: err.message };
  if (err.details) body.details = err.details;
  if (status === 500) console.error(err);
  res.status(status).json(body);
});

Unhandled Errors

If no error handler is registered, Http-native responds with a generic 500 Internal Server Error. Always register an error handler in production.

Clone this wiki locally