Improved getModelFolderContents error handling readability

This commit is contained in:
Alexander Cerutti
2023-04-19 23:51:40 +02:00
parent 1e22b974d6
commit ccb5e72c8c

View File

@@ -50,30 +50,52 @@ export default async function getModelFolderContents(
.reduce((acc, current) => ({ ...acc, ...current }), {}); .reduce((acc, current) => ({ ...acc, ...current }), {});
return modelRecords; return modelRecords;
} catch (_err) { } catch (err) {
const err = _err as NodeJS.ErrnoException; if (!isErrorErrNoException(err) || !isMissingFileError(err)) {
throw err;
}
if (err?.code === "ENOENT") { if (isFileReadingFailure(err)) {
if (err.syscall === "open") {
// file opening failed
throw new Error( throw new Error(
Messages.format( Messages.format(
Messages.MODELS.FILE_NO_OPEN, Messages.MODELS.FILE_NO_OPEN,
JSON.stringify(err), JSON.stringify(err),
), ),
); );
} else if (err.syscall === "scandir") { }
// directory reading failed
if (isDirectoryReadingFailure(err)) {
throw new Error( throw new Error(
Messages.format(Messages.MODELS.DIR_NOT_FOUND, err.path), Messages.format(Messages.MODELS.DIR_NOT_FOUND, err.path),
); );
} }
}
throw err; throw err;
} }
} }
function isErrorErrNoException(err: unknown): err is NodeJS.ErrnoException {
return Object.prototype.hasOwnProperty.call(err, "errno");
}
function isMissingFileError(
err: unknown,
): err is NodeJS.ErrnoException & { code: "ENOENT" } {
return (err as NodeJS.ErrnoException).code === "ENOENT";
}
function isDirectoryReadingFailure(
err: NodeJS.ErrnoException,
): err is NodeJS.ErrnoException & { syscall: "scandir" } {
return err.syscall === "scandir";
}
function isFileReadingFailure(
err: NodeJS.ErrnoException,
): err is NodeJS.ErrnoException & { syscall: "open" } {
return err.syscall === "open";
}
/** /**
* Reads sequentially * Reads sequentially
* @param filePath * @param filePath