-
Notifications
You must be signed in to change notification settings - Fork 2
Error Handling
BrewedSys edited this page Mar 30, 2026
·
1 revision
Http-native provides built-in error handling to catch and respond to errors gracefully.
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 |
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);
});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);
});If no error handler is registered, Http-native responds with a generic 500 Internal Server Error. Always register an error handler in production.
Http-native is open to everyone, but we have strict regulations and licensing fees for large organizations