sharp-db
Version:
Classes for running SQL and building select queries for MySQL in Node
41 lines (39 loc) • 1.52 kB
JavaScript
/**
* Give MySQL error a more verbose `stack` and `message`
* @param {Error} error Error object thrown by msql2 library
* @param {Object} options Options generated by various Db functions
* @property {String} options.sql The final SQL string that was executed
* @property {Object} options.bound Key-value pairs of bound values
*/
function decorateError(error, options = {}) {
// pull out existing properties and provide defaults
const code = error.code || 'ERROR';
const errno = error.errno || '-1';
const sqlState = error.sqlState || 'N/A';
const stack = error.stack || '';
const sqlMessage = error.sqlMessage || error.message;
let sqlSnippet = '';
if (options.sql) {
error.sql = options.sql;
const fullSql = options.sql.trim().replace(/\n\s*/g, '\n');
if (fullSql.length >= 300) {
sqlSnippet = fullSql.slice(0, 297) + '...';
} else {
sqlSnippet = fullSql;
}
sqlSnippet = `Query:\n${sqlSnippet}`;
}
// take stack but remove first line
const stackWithoutError = stack.split('\n').slice(1).join('\n');
// build a message with code, errno, sqlState, sqlMessage and SQL snippet
const newMessage =
`[${code}] ${errno} (${sqlState}): ${sqlMessage}\n${sqlSnippet}`.trim();
// build a stack with the error text and remaining stack
const newStack = `${newMessage}\n${stackWithoutError}`;
// add these new values as properties
error.stack = newStack;
error.message = newMessage;
error.bound = options.bound || {};
error.name = 'MySQLError';
}
module.exports = decorateError;