You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
2.0 KiB
JavaScript

'use strict';
const createError = require("create-error");
const pgErrorCodes = require("pg-error-codes");
const DatabaseError = require("../database-error.js");
const getTable = require("../get-table");
let InvalidTypeError = createError(DatabaseError, "InvalidTypeError");
/* NOTE: error messages vary. Eg. for boolean-type columns, it states "for type boolean", but for integer-type columns, it starts "for integer". */
let messageRegex = /^(?:(.+) - )?invalid input syntax for(?: type)? ([^:]+)(?:: "(.+)")?$/;
module.exports = {
error: InvalidTypeError,
errorName: "InvalidTypeError",
check: function checkType(error) {
return (
// PostgreSQL (via `pg`):
(error.length != null && error.file != null && error.line != null && error.routine != null && error.code === "22P02" && error.message.includes("invalid input syntax for"))
)
},
convert: function convertError(error) {
let messageMatch = messageRegex.exec(error.message);
if (messageMatch == null) {
/* TODO: Update other error parsing modules to display the original error message here as well. */
throw new Error(`Encountered unknown error format for error message: ${error.message}`);
}
let [_, query, expectedType, value] = messageMatch;
let table = getTable(query);
let message;
/* TODO: `value` can be undefined! */
if (table != null) {
message = `Value <${value}> is of the wrong type for a '${expectedType}'-type column (in table '${table}')`;
} else {
message = `Value <${value}> is of the wrong type for a '${expectedType}'-type column`;
}
return new InvalidTypeError(message, {
originalError: error,
pgCode: error.code,
code: pgErrorCodes[error.code],
query: query,
table: table,
expectedType: expectedType,
value: value,
});
}
};