Catch Express API errors and send an actionable alert
Add one Express 5 error handler that records failed requests in Butters with a request ID, route, and error type, then alerts the team without leaking customer data.
A 500 response tells the caller something failed. It does not tell your team which operation broke, how to find the matching log, or whether anyone needs to act. A small error handler can close that gap: send one event with a stable route, an error type, and a request ID, then notify your team.
This example uses Express 5 and the Butters server SDK. It reports unexpected server errors only; validation and authentication failures should stay ordinary 4xx responses.
Install the SDK
npm install @getbutters/js Set BUTTERS_API_KEY and BUTTERS_PROJECT_ID in your server environment. Keep the event key on the server.
Add a request ID and one error handler
import express from 'express';
import { randomUUID } from 'node:crypto';
import { Butters } from '@getbutters/js/server';
const app = express();
const butters = new Butters({
key: process.env.BUTTERS_API_KEY,
project: process.env.BUTTERS_PROJECT_ID,
timeoutMs: 1500,
});
app.use((req, res, next) => {
res.locals.requestId = randomUUID();
res.setHeader('X-Request-ID', res.locals.requestId);
next();
});
// Register your routes here.
app.use(async (err, req, res, next) => {
if (res.headersSent) return next(err);
const error = err instanceof Error ? err : new Error('Unknown error');
const proposedStatus = Number(err?.status ?? err?.statusCode);
const status = proposedStatus >= 400 && proposedStatus < 600
? proposedStatus
: 500;
// Your server logs retain the full stack, keyed by this ID.
console.error({ requestId: res.locals.requestId, error });
if (status >= 500) {
try {
await butters.track('errors', 'Express API request failed', {
description: error.name,
icon: '🚨',
tags: ['api', 'server-error'],
metadata: {
request_id: res.locals.requestId,
method: req.method,
route: String(req.route?.path ?? 'unmatched'),
error_type: error.name,
status,
},
notify: true,
});
} catch (reportError) {
console.error('Could not report error to Butters', reportError);
}
}
res.status(status).json({
error: status >= 500 ? 'Internal server error' : 'Request failed',
requestId: res.locals.requestId,
});
}); Register the four-argument error handler after your routes. In Express 5, a rejected promise in an async route is passed to it automatically. If a response has already started, next(err) lets Express finish handling that failure. See the Express error-handling guide for those behaviors.
Make the alert useful and safe
The event gives a responder an operation, an error type, and the request ID needed to find the full server log. The response returns the same ID to a customer or support agent. The code deliberately sends no request body, raw URL, headers, stack trace, or error message to Butters: those fields can contain tokens or customer data. If a route needs more context, add a small, explicitly approved field such as a job type or payment provider.
notify: true sends the event to the notification destinations configured for the project. Reserve that for failures someone should investigate. For a noisy endpoint, start by recording every 500 with notify: false, then notify only on a defined condition such as the first failure in a window or a high-value operation. This example awaits reporting with a short timeout so a reporting failure cannot prevent the API response indefinitely. Tune the timeout for your latency budget.
Check the result
- Trigger a known test error in a nonproduction environment.
- Confirm the client receives a 500 and an
X-Request-IDheader. - Find the Butters error event and verify its request ID matches the server log.
- Confirm the configured destination receives one alert and that no sensitive request data appears in the event.
Once that loop works, repeat it for the specific operations your team actually owns. A page that says “API failed” is easy to ignore; an alert with a route and a request ID gives someone a place to start.