Fix Improper Error Handling in Sails
Improper error handling in Sails.js often leads to Information Exposure. By default, passing a raw error object to 'res.serverError()' can leak stack traces, environment variables, and database schema details (Waterline/PostgreSQL/MySQL errors) to the client. In a production environment, this provides an attacker with the exact blueprint of your backend architecture, enabling precise exploitation.
The Vulnerable Pattern
// api/controllers/UserController.js
module.exports = {
profile: async function (req, res) {
try {
let user = await User.findOne({ id: req.param('id') });
return res.json(user);
} catch (err) {
// VULNERABILITY: Sending the raw 'err' object to the client.
// This leaks database internals and stack traces if NODE_ENV is not 'production'.
return res.serverError(err);
}
}
};
The Secure Implementation
To fix this, implement a strict separation between internal logging and external responses. First, never pass the 'err' object directly to response helpers like 'res.serverError()'. Second, customize the global response handler in 'api/responses/serverError.js' to ensure that if 'NODE_ENV' is set to 'production', all detailed error data is stripped before reaching the network. Use unique error reference codes (UUIDs or short strings) to allow users to report issues without seeing the underlying cause, while developers can find the full trace in the internal logs.
// api/controllers/UserController.js module.exports = { profile: async function (req, res) { try { let user = await User.findOne({ id: req.param('id') }); if (!user) return res.notFound({ error: 'User not found' }); return res.json(user); } catch (err) { // SECURE: Log the actual error internally for debugging sails.log.error(`User lookup failed: ${err.stack}`);// Return a sanitized, generic error message to the client return res.serverError({ message: 'An internal server error occurred.', reference: 'ERR_USER_001' }); }} };
// Also, ensure api/responses/serverError.js is configured to strip details: // module.exports = function serverError(data) { // if (process.env.NODE_ENV === ‘production’) return this.res.status(500).send(‘Internal Server Error’); // return this.res.status(500).json(data); // };
Your Sails API
might be exposed to Improper Error Handling
74% of Sails apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.