Error Handling By a Middleware #javascript #wecommit100xshare
customError intgrate into middleware

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:

defined errorHanler
ussing apply middleware
add class CustomError


update class DatabaseError


update code


integrate custom error into middleware

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,
    }))
}        
example write log for the error


reference article



Stanislav Sorokin

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!

回复
Hardik Agnihotri

Full Stack Developer | MERN Stack, Next.js & TypeScript | Building Scalable, User-Centric Web Applications | Open to Startup & Innovation Opportunities

3 个月

great article

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了