Last active
April 9, 2023 02:44
-
-
Save mtorre4580/d7845978cfea30b155d77968ebed974c to your computer and use it in GitHub Desktop.
Example error handler in node.js for APIs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require("express"); | |
const app = express(); | |
const PORT = process.env.PORT || 3001; | |
// Replace with your logger | |
const logger = console; | |
/** | |
* Create the errors to send to the client | |
*/ | |
class AppError extends Error { | |
constructor(tag, message, status = 500, cause = null) { | |
super(message); | |
this.tag = tag; | |
this.status = status; | |
this.cause = cause; | |
} | |
} | |
// Example endpoint to send random error | |
app.get("/hello", (req, res, next) => { | |
if (Math.random() < 0.5) { | |
return res.json({ msg: "world" }); | |
} | |
return next(new AppError("hello_handler", "Can't resolve the current service is failed", 503)); | |
}); | |
// Middleware to handle all the errors in the app and log in your custom logger (datadog, newrelic) | |
app.use((error, req, res, next) => { | |
if (error) { | |
const { tag, status = 500, message } = error; | |
logger.error(`[${tag}] ${status} - ${message}`); | |
return res | |
.status(status) | |
.json({ message: message || "Internal Server Error" }); | |
} | |
return next(); | |
}); | |
app.listen(PORT, () => { | |
logger.info(`API listen in ${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment