human-readable-errors
Version:
A library to transform complex error messages into human-readable solutions.
40 lines (35 loc) • 1.45 kB
JavaScript
/**
* Parses a Node.js error string to extract error details.
* @param {string} errorString - The error message or stack trace.
* @returns {Object} - Parsed error details, including type, description, file, line number, and column number.
*/
function nodeParser(errorString) {
// console.log(errorString, "fffffffffffff errorString");
if (!errorString || typeof errorString !== "string") {
return {
type: "UnknownError",
description: "Invalid error string provided.",
file: null,
lineNumber: null,
columnNumber: null,
};
}
// Matches the first line of an error message to extract the type and message
const errorPattern = /^(?<type>[a-zA-Z]+Error)\s*:\s*(?<description>.+)$/m;
// Matches the first occurrence of a file, line, and column in a stack trace
const stackPattern = /\((?<file>[^:]+):(?<line>\d+):(?<column>\d+)\)/;
const errorMatch = errorString.match(errorPattern);
const stackMatch = errorString.match(stackPattern);
return {
type: errorMatch?.groups?.type || "UnknownError",
description: errorMatch?.groups?.description || "Unknown description",
file: stackMatch?.groups?.file || null,
lineNumber: stackMatch?.groups?.line
? parseInt(stackMatch.groups.line, 10)
: null,
columnNumber: stackMatch?.groups?.column
? parseInt(stackMatch.groups.column, 10)
: null,
};
}
export { nodeParser };