DEV Community

Cover image for How Express.js detects if a middleware is an error or request one
Sanjar Afaq
Sanjar Afaq

Posted on

How Express.js detects if a middleware is an error or request one

Situation

Suppose we have this code:

const express = require('express');
const app = express();

// usual code - app.METHOD, app.use, routers etc

// below: wont' be treated as error middleware
app.use((req, res, next) => {}); 


// below: will be treated as an error middleware
app.use((err, req, res, next) => {});
Enter fullscreen mode Exit fullscreen mode

 

Question

How does Express.js know which one is an error middleware, given both app.use take a callback (function).
 
 

Explanation

Well it's quite simple. JS allows us to calculate the number of params in a function (MDN). Syntax example:

const mySumFunction = (a, b) => { return a + b; };

console.log(mySumFunction.length); // 2
Enter fullscreen mode Exit fullscreen mode

This was surprising for me since I thought callback (or functions in general) are black-boxes, we could just call them, and that was it. But no.
 
 

Evidence

Coming back to the topic, Express internally does this .length to decide if the middleware is a "request" or an "error" one.

See (Express.js repo at GitHub): https://github.com/expressjs/express/blob/3531987844e533742f1159b0c3f1e07fad2e4597/lib/router/layer.js#L89

Top comments (0)