How to Log Errors in Express: Simple Error Logging Guide
In Express, you log errors by creating an error-handling middleware with
app.use((err, req, res, next) => { ... }). Inside this middleware, use console.error(err) or an external logger to record error details before sending a response.Syntax
An error-handling middleware in Express has four parameters: err, req, res, and next. You place this middleware after all other routes and middleware.
err: The error object caught by Express.req: The request object.res: The response object.next: The next middleware function.
Inside, you log the error and send a response to the client.
javascript
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});Example
This example shows a simple Express app that triggers an error and logs it using error-handling middleware.
javascript
import express from 'express'; const app = express(); app.get('/', (req, res) => { throw new Error('Oops! Something went wrong.'); }); // Error-handling middleware app.use((err, req, res, next) => { console.error('Error caught:', err.message); res.status(500).send('Internal Server Error'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Error caught: Oops! Something went wrong.
Common Pitfalls
- Not placing error middleware last: It must come after all routes to catch errors.
- Forgetting the
errparameter: Middleware without four parameters won't catch errors. - Not logging error details: Logging only the message may miss stack traces.
- Sending multiple responses: Always end the response after logging to avoid errors.
javascript
/* Wrong: Missing 'err' parameter, won't catch errors */ app.use((req, res, next) => { console.error('This is not an error handler'); next(); }); /* Right: Proper error handler with four parameters */ app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Server error'); });
Quick Reference
- Use
app.use((err, req, res, next) => { ... })for error logging middleware. - Log full error stack with
console.error(err.stack)for better debugging. - Place error middleware after all routes.
- Send a response to avoid hanging requests.
Key Takeaways
Always use error-handling middleware with four parameters to catch errors in Express.
Log the full error stack to get detailed information for debugging.
Place error middleware after all other routes and middleware.
Send a response inside the error handler to avoid hanging requests.
Use external logging tools for production apps to track errors better.