'Error thrown in middleware not caught by error handling middleware
I have the following error handling middleware:
class ErrorHandler extends Error {
constructor(statusCode, message) {
super();
this.statusCode = statusCode;
this.message = message;
}
}
async function handleError (err, req, res, next) {
const { code, statusCode, message } = err;
let msg = code === 'ERR_HMAC_AUTH_INVALID' ? 'Invalid HMAC' : message
res.status(statusCode).json({
status: "error",
statusCode,
message
});
};
module.exports = {
ErrorHandler,
handleError
}
I also have the following authorization middleware:
async function handleAuthentication (req, res, next) {
const authorization = req.headers['authorization'];
if (typeof(authorization) === 'undefined'){
throw new ErrorHandler(401, 'Missing Authorization');
}
}
module.exports = {
handleAuthentication
}
My server.js looks like this:
const app = express();
app.use(cors({
credentials: true,
origin: "http://localhost:3000",
methods: ['GET','POST','DELETE','UPDATE','PUT','PATCH']
}))
app.use(express.json({limit: '5mb'}));
app.use(handleError);
app.use(handleAuthentication);
Why does the error handling middleware not catch the error thrown by the authorization middleware? I can see in the debug console that I get an uncaught exception.
Thanks
Solution 1:[1]
The order in which middleware are listed in an application matters. In your server.js file the handleError middleware is run before the handleAuthentication middleware. This means that the handleError middleware runs before the error is thrown. Try reversing them:
const app = express();
app.use(cors({
credentials: true,
origin: "http://localhost:3000",
methods: ['GET','POST','DELETE','UPDATE','PUT','PATCH']
}))
app.use(express.json({limit: '5mb'}));
app.use(handleAuthentication);
app.use(handleError);
Also when you throw the error:
throw new ErrorHandler('Missing Authorization', 401);
the order of your parameters seems to be different from the ErrorHandler constructor:
constructor(statusCode, message)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
