Skip to content

Instantly share code, notes, and snippets.

@Oluwasetemi
Forked from w3cj/try-parse-env.ts
Created June 8, 2025 02:32
Show Gist options
  • Save Oluwasetemi/ee521c88903ee99cd8bc0f0c79737b58 to your computer and use it in GitHub Desktop.
Save Oluwasetemi/ee521c88903ee99cd8bc0f0c79737b58 to your computer and use it in GitHub Desktop.
/* eslint-disable node/no-process-env */
import type { ZodObject, ZodRawShape } from "zod";
import { ZodError } from "zod";
export default function tryParseEnv<T extends ZodRawShape>(
EnvSchema: ZodObject<T>,
buildEnv: Record<string, string | undefined> = process.env,
) {
try {
EnvSchema.parse(buildEnv);
}
catch (error) {
if (error instanceof ZodError) {
let message = "Missing required values in .env:\n";
error.issues.forEach((issue) => {
message += `${issue.path[0]}\n`;
});
const e = new Error(message);
e.stack = "";
throw e;
}
else {
console.error(error);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment