Error Handling By a Middleware #javascript #wecommit100xshare
What is a Middleware
A middleware in brief is simply a function that intercepts the request in order to apply certain logic before it reaches its destination: the request handler. Not only they intecept the request, but also the response. After the request handler does its job when receiving the request, the response also passes again through the same middleware that intercepted the request before reaching its destination: the client or web browser.
Error handling in Express.js happens by simply defining a middleware (function) that accepts 4 parameters: error, request, response, next as follows:
How to handling error in Javascripit
function funcLoop(x) {
console.log(x);
decodeURIComponent("%"); // URIError
throw new RangeError("The argument must be between -500 and 500."); // RangeError
throw new EvalError("Hello"); // EvalError
// const r = x + a; // ReferenceError
}
const x = 0
try {
funcLoop(x);
} catch (err) {
console.log(`[funcLoop](${JSON.stringify(x)})`, JSON.stringify({
name: err.name,
message: err.message,
stack: err.stack,
}))
}
Owner and Founder at Bles Software | Building the Future ?? Creating Enterprise SaaSs and Web Applications ??
2 周Hey Dat, I couldn't agree more with your post on error handling through middleware in JavaScript. It's a game-changer for developers looking to optimize their code!
Full Stack Developer | MERN Stack, Next.js & TypeScript | Building Scalable, User-Centric Web Applications | Open to Startup & Innovation Opportunities
3 个月great article