diff --git a/lib/mysql.js b/lib/mysql.js index e8f7165c6..b1d80e31d 100644 --- a/lib/mysql.js +++ b/lib/mysql.js @@ -14,9 +14,9 @@ const mysql = require('mysql2'); const SqlConnector = require('loopback-connector').SqlConnector; const ParameterizedSQL = SqlConnector.ParameterizedSQL; const EnumFactory = require('./enumFactory').EnumFactory; +const normalizeMySQLError = require('./normalize-error'); const debug = require('debug')('loopback:connector:mysql'); -const setHttpCode = require('./set-http-code'); /** * @module loopback-connector-mysql @@ -190,6 +190,7 @@ function generateOptions(settings) { } return options; } + /** * Execute the sql statement * @@ -215,7 +216,11 @@ MySQL.prototype.executeSQL = function(sql, params, options, callback) { connection.release(); } if (err) { - err = setHttpCode(err); + if (debugEnabled) { + debug('Raw driver error intercepted: %O', err); + } + // Transform raw MySQL driver error into standard LoopBack DB error + err = normalizeMySQLError(err); } callback && callback(err, result); } diff --git a/lib/normalize-error.js b/lib/normalize-error.js new file mode 100644 index 000000000..08ee8d847 --- /dev/null +++ b/lib/normalize-error.js @@ -0,0 +1,66 @@ +'use strict'; + +/** + * Normalizes MySQL-specific error numbers to standard, protocol-neutral domain codes. + */ +module.exports = function(err) { + if (!err || !err.errno) return err; + + switch (err.errno) { + // 1. Data Integrity & Constraints + case 1062: // ER_DUP_ENTRY + err.code = 'UNIQUE_CONSTRAINT_VIOLATION'; + break; + case 1215: // ER_CANNOT_ADD_FOREIGN + case 1216: // ER_NO_REFERENCED_ROW + case 1217: // ER_ROW_IS_REFERENCED + case 1451: // ER_ROW_IS_REFERENCED_2 + case 1452: // ER_NO_REFERENCED_ROW_2 + err.code = 'FOREIGN_KEY_VIOLATION'; + break; + case 1048: // ER_BAD_NULL_ERROR + err.code = 'NOT_NULL_VIOLATION'; + break; + case 3819: // ER_CHECK_CONSTRAINT_VIOLATED + err.code = 'CHECK_CONSTRAINT_VIOLATION'; + break; + + // 2. Schema & Object Definitions + case 1051: // ER_BAD_TABLE_ERROR + case 1146: // ER_NO_SUCH_TABLE + err.code = 'TABLE_NOT_FOUND'; + break; + case 3105: // MySQL Generated column value ignored/disallowed + case 1906: // MariaDB Generated column value ignored/disallowed + err.code = 'GENERATED_COLUMN_VIOLATION'; + break; + + // 3. Data Formatting & Types + case 1366: // ER_TRUNCATED_WRONG_VALUE_FOR_FIELD + case 1406: // ER_DATA_TOO_LONG + err.code = 'DATA_TYPE_MISMATCH'; + break; + + // 4. Concurrency & Execution + case 1205: // ER_LOCK_WAIT_TIMEOUT + case 1213: // ER_LOCK_DEADLOCK + err.code = 'LOCK_CONFLICT'; + break; + case 1907: // Query timeout + case 3024: // Statement timeout + err.code = 'QUERY_TIMEOUT'; + break; + case 1064: // ER_PARSE_ERROR (Syntax error) + err.code = 'SYNTAX_ERROR'; + break; + + // 5. Infrastructure & Connection + case 1040: // ER_CON_COUNT_ERROR (Too many connections) + case 1053: // PROTOCOL_CONNECTION_LOST + case 2006: // CR_SERVER_GONE_ERROR (MySQL server has gone away) + case 2013: // CR_SERVER_LOST (Lost connection to MySQL server during query) + err.code = 'CONNECTION_FAILURE'; + break; + } + return err; +}; diff --git a/lib/set-http-code.js b/lib/set-http-code.js deleted file mode 100644 index ced518d93..000000000 --- a/lib/set-http-code.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright IBM Corp. 2017,2019. All Rights Reserved. -// Node module: loopback-connector-mysql -// This file is licensed under the MIT License. -// License text available at https://opensource.org/licenses/MIT - -'use strict'; - -const _ = require('lodash'); - -const codes = { - '404': [ - 'ER_DB_DROP_EXISTS', - 'ER_BAD_TABLE_ERROR', - ], - '422': [ - 'ER_DUP_ENTRY', - 'ER_CANT_CREATE_DB', - 'ER_DB_CREATE_EXISTS', - 'ER_TABLE_EXISTS_ERROR', - ], -}; - -/*! - * Translate MySQL error codes into HTTP Errors. - * If an error would be better represented by a code that isn't 500, - * add your SQL error to the correct HTTP code array above! - */ -module.exports = function(err) { - let code = ''; - if (err && err.code) code = err.code; - if (!err) { - return; - } else if (!(err instanceof Error)) { - err = new Error(err); // Sucks that we weren't given an error object... - } - // Find error prefix - const msg = err.message; - const sqlError = msg.substring(0, msg.indexOf(':')) || code; - - for (const code in codes) { - if (_.includes(codes[code], sqlError)) { - err.statusCode = code; - } - } - if (!err.statusCode) err.statusCode = 500; - return err; -}; diff --git a/test/mysql.test.js b/test/mysql.test.js index 44c02808b..37de1e9c2 100644 --- a/test/mysql.test.js +++ b/test/mysql.test.js @@ -8,6 +8,7 @@ const async = require('async'); const should = require('./init.js'); const sinon = require('sinon'); const List = require('loopback-datasource-juggler/lib/list'); +const normalizeMySQLError = require('../lib/normalize-error.js'); let Post, PostWithStringId, PostWithUniqueTitle, PostWithNumId, Student, db; @@ -1076,6 +1077,38 @@ describe('mysql', function() { }); }); + describe('database error normalization', function() { + it('should normalize duplicate key error (1062) to UNIQUE_CONSTRAINT_VIOLATION', function() { + const mockErr = new Error('Duplicate entry'); + mockErr.errno = 1062; + + const normalized = normalizeMySQLError(mockErr); + + should.exist(normalized); + normalized.should.have.property('code', 'UNIQUE_CONSTRAINT_VIOLATION'); + }); + + it('should normalize foreign key violation (1452) to FOREIGN_KEY_VIOLATION', function() { + const mockErr = new Error('Foreign Key constraint is failing'); + mockErr.errno = 1452; + + const normalized = normalizeMySQLError(mockErr); + + should.exist(normalized); + normalized.should.have.property('code', 'FOREIGN_KEY_VIOLATION'); + }); + + it('should normalize missing table error (1146) to TABLE_NOT_FOUND', function() { + const mockErr = new Error("Table 'myapp_test.NonExistentTable' doesn't exist"); + mockErr.errno = 1146; + + const normalized = normalizeMySQLError(mockErr); + + should.exist(normalized); + normalized.should.have.property('code', 'TABLE_NOT_FOUND'); + }); + }); + function deleteAllModelInstances() { const models = [ Post, PostWithStringId, PostWithUniqueTitle, PostWithNumId, Student, diff --git a/test/normalize-error.test.js b/test/normalize-error.test.js new file mode 100644 index 000000000..49e1a2374 --- /dev/null +++ b/test/normalize-error.test.js @@ -0,0 +1,104 @@ +'use strict'; + +const should = require('./init.js'); +const normalizeMySQLError = require('../lib/normalize-error.js'); + +describe('normalizeMySQLError', function() { + describe('Data Integrity & Constraints', function() { + it('maps 1062 to UNIQUE_CONSTRAINT_VIOLATION', function() { + const err = {errno: 1062}; + normalizeMySQLError(err); + should.equal(err.code, 'UNIQUE_CONSTRAINT_VIOLATION'); + }); + + it('maps foreign key error numbers (1215, 1216, 1217, 1451, 1452) to FOREIGN_KEY_VIOLATION', function() { + [1215, 1216, 1217, 1451, 1452].forEach(errno => { + const err = {errno}; + normalizeMySQLError(err); + should.equal(err.code, 'FOREIGN_KEY_VIOLATION'); + }); + }); + + it('maps 1048 to NOT_NULL_VIOLATION', function() { + const err = {errno: 1048}; + normalizeMySQLError(err); + should.equal(err.code, 'NOT_NULL_VIOLATION'); + }); + + it('maps 3819 to CHECK_CONSTRAINT_VIOLATION', function() { + const err = {errno: 3819}; + normalizeMySQLError(err); + should.equal(err.code, 'CHECK_CONSTRAINT_VIOLATION'); + }); + }); + + describe('Schema & Object Definitions', function() { + it('maps table not found error numbers (1051, 1146) to TABLE_NOT_FOUND', function() { + [1051, 1146].forEach(errno => { + const err = {errno}; + normalizeMySQLError(err); + should.equal(err.code, 'TABLE_NOT_FOUND'); + }); + }); + + it('maps generated column error numbers (3105, 1906) to GENERATED_COLUMN_VIOLATION', function() { + [3105, 1906].forEach(errno => { + const err = {errno}; + normalizeMySQLError(err); + should.equal(err.code, 'GENERATED_COLUMN_VIOLATION'); + }); + }); + }); + + describe('Data Formatting & Types', function() { + it('maps data type mismatch error numbers (1366, 1406) to DATA_TYPE_MISMATCH', function() { + [1366, 1406].forEach(errno => { + const err = {errno}; + normalizeMySQLError(err); + should.equal(err.code, 'DATA_TYPE_MISMATCH'); + }); + }); + }); + + describe('Concurrency & Execution', function() { + it('maps lock conflict error numbers (1205, 1213) to LOCK_CONFLICT', function() { + [1205, 1213].forEach(errno => { + const err = {errno}; + normalizeMySQLError(err); + should.equal(err.code, 'LOCK_CONFLICT'); + }); + }); + + it('maps query timeout error numbers (1907, 3024) to QUERY_TIMEOUT', function() { + [1907, 3024].forEach(errno => { + const err = {errno}; + normalizeMySQLError(err); + should.equal(err.code, 'QUERY_TIMEOUT'); + }); + }); + + it('maps 1064 to SYNTAX_ERROR', function() { + const err = {errno: 1064}; + normalizeMySQLError(err); + should.equal(err.code, 'SYNTAX_ERROR'); + }); + }); + + describe('Infrastructure & Connection', function() { + it('maps connection failure error numbers (1040, 1053, 2006, 2013) to CONNECTION_FAILURE', function() { + [1040, 1053, 2006, 2013].forEach(errno => { + const err = {errno}; + normalizeMySQLError(err); + should.equal(err.code, 'CONNECTION_FAILURE'); + }); + }); + }); + + describe('Fallback behavior', function() { + it('returns original error unchanged if errno is unrecognized or missing', function() { + const err = {errno: 9999, message: 'unknown'}; + const result = normalizeMySQLError(err); + should.equal(result.code, undefined); + }); + }); +}); diff --git a/test/set-http-code.test.js b/test/set-http-code.test.js deleted file mode 100644 index f07a537a8..000000000 --- a/test/set-http-code.test.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright IBM Corp. 2017,2019. All Rights Reserved. -// Node module: loopback-connector-mysql -// This file is licensed under the MIT License. -// License text available at https://opensource.org/licenses/MIT - -'use strict'; - -const setHttpCode = require('../lib/set-http-code'); -const should = require('./init.js'); - -describe('setHttpCode', function() { - describe('should set statusCode', function() { - testErrorCode('404 on db not found', 'ER_DB_DROP_EXISTS: Nope', 404); - testErrorCode('404 on table not found', 'ER_BAD_TABLE_ERROR: Nope', 404); - - testErrorCode('422 on duplicates', 'ER_DUP_ENTRY: Duplicate entry', 422); - testErrorCode('422 on cannot create db', 'ER_CANT_CREATE_DB: Oops', 422); - testErrorCode('422 on db already exists', 'ER_DB_CREATE_EXISTS: Oops', 422); - testErrorCode('422 on db not found', 'ER_TABLE_EXISTS_ERROR: Nope', 422); - - testErrorCode('500 on unknown errors', 'FATAL: Sadness happened', 500); - - function testErrorCode(name, msg, expected) { - it(name, function() { - let err = new Error(msg); - err = setHttpCode(err); - should.exist(err.statusCode); - should.equal(err.statusCode, expected); - }); - } - }); - - it('should set statusCode from code', function() { - let err = { - message: 'Duplicate entry \'value\' for key \'key_name\'', - code: 'ER_DUP_ENTRY', - }; - err = setHttpCode(err); - should.exist(err.statusCode); - should(err instanceof Error); - should.equal(err.statusCode, 422); - }); - - it('should do nothing without error', function() { - should.doesNotThrow(setHttpCode); - }); - - it('should convert strings to errors', function() { - let err = 'REALLY_BAD: Something truly awful occurred.'; - err = setHttpCode(err); - should.exist(err.statusCode); - should(err instanceof Error); - should.equal(err.statusCode, 500); - }); -});