'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) { throw new Error("Encountered unknown error format"); } let [_, query, expectedType, value] = messageMatch; let table = getTable(query); let message; 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 '${enumType}'`; } return new InvalidTypeError(message, { originalError: error, pgCode: error.code, code: pgErrorCodes[error.code], query: query, table: table, expectedType: expectedType, value: value, }); } };