@visulima/fs
Version:
Human friendly file system utilities for Node.js
53 lines (52 loc) • 1.91 kB
TypeScript
/**
* Custom error class for handling JSON parsing or related errors.
* It can optionally include a file name and a code frame for better debugging.
* @example
* ```javascript
* import { JSONError } from "@visulima/fs/error";
* import { readJsonSync } from "@visulima/fs"; // Or any function that might throw this
* import { join } from "node:path";
*
* try {
* // Imagine readJsonSync encounters a malformed JSON file and throws JSONError
* // Forcing the scenario for demonstration:
* const simulateJsonError = (filePath, content) => {
* const err = new JSONError(`Unexpected token '}' at position 15`);
* err.fileName = filePath;
* // A real implementation might generate a code frame using a library
* err.codeFrame = ` 13 | "key": "value",
* > 14 | "anotherKey": "anotherValue",}
* | ^
* 15 | "lastKey": "end"
* `;
* throw err;
* };
*
* simulateJsonError(join("path", "to", "corrupted.json"), '{ "key": "value", "anotherKey": "anotherValue",} ');
* // const jsonData = readJsonSync(join("path", "to", "corrupted.json"));
* } catch (error) {
* if (error instanceof JSONError) {
* console.error(`JSON Error: ${error.message}`);
* // message property will include fileName and codeFrame if they were set.
* // console.error(`File: ${error.fileName}`);
* // console.error(`Code Frame:\n${error.codeFrame}`);
* } else {
* console.error("An unexpected error occurred:", error);
* }
* }
* ```
*/
declare class JSONError extends Error {
#private;
fileName: string | undefined;
codeFrame: string | undefined;
readonly name = "JSONError";
/**
* Creates a new JSONError instance.
* @param message The primary error message.
*/
constructor(message: string);
get message(): string;
set message(message: string);
}
export default JSONError;