chaos-injector
Version:
Chaos engineering middleware for testing API resilience
46 lines (40 loc) • 1.65 kB
JavaScript
// ChaosInjector/middlewares/randomFailure.js
function randomFailure(options = {}) {
const { failureRate = 0.0, errorTypes = ['500'] } = options;
return function(req, res, next) {
const randomStatus = Math.random();
if (randomStatus < failureRate) {
const errorType = errorTypes[Math.floor(Math.random() * errorTypes.length)];
switch (errorType) {
case '400':
return res.status(400).json({ error: 'Bad Request' });
case '401':
return res.status(401).json({ error: 'Unauthorized' });
case '403':
return res.status(403).json({ error: 'Forbidden' });
case '404':
return res.status(404).json({ error: 'Not Found' });
case '405':
return res.status(405).json({ error: 'Method Not Allowed' });
case '409':
return res.status(409).json({ error: 'Conflict' });
case '429':
return res.status(429).json({ error: 'Too Many Requests' });
case '500':
return res.status(500).json({ error: 'Internal Server Error' });
case '502':
return res.status(502).json({ error: 'Bad Gateway' });
case '503':
return res.status(503).json({ error: 'Service Unavailable' });
case '504':
return res.status(504).json({ error: 'Gateway Timeout' });
case 'empty':
return res.status(500).send(); // Sending empty response with 500 status
default:
return next(new Error(`Unsupported error type: ${errorType}`));
}
}
next();
};
}
module.exports = randomFailure;