'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 UndefinedColumnError = createError(DatabaseError, "UndefinedColumnError"); let messageRegex = /^(.+) - column "([^"]+)" (?:of relation "([^"]+)" )?does not exist$/; module.exports = { error: UndefinedColumnError, errorName: "UndefinedColumnError", check: function checkType(error) { return ( // PostgreSQL (via `pg`): (error.length != null && error.file != null && error.line != null && error.routine != null && error.code === "42703") ) }, convert: function convertError(error) { let messageMatch = messageRegex.exec(error.message); if (messageMatch == null) { throw new Error("Encountered unknown error format"); } let [_, query, column, table] = messageMatch; let errorMessage; if (table != null) { errorMessage = `The '${column}' column does not exist in the '${table}' table`; } else { /* TODO: Maybe try to extract this from the query... somehow? */ errorMessage = `The '${column}' column does not exist in (unknown table)`; } return new UndefinedColumnError(errorMessage, { originalError: error, pgCode: error.code, code: pgErrorCodes[error.code], query: query, table: table, column: column, }); } };