From 6dff9bbdb856b86ab516b58ebe34d465d0f671ae Mon Sep 17 00:00:00 2001 From: Erica Marigold Date: Thu, 28 Mar 2024 16:12:44 +0530 Subject: [PATCH] feat: basic error handling Currently, this implements a simple runtime error which is raised when either the private or public key generation fail. In the future, it would make sense to include some runtime argument validation, and a more parseable error. --- src/index.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/index.ts b/src/index.ts index f13e880..1b57ca8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,16 +16,19 @@ export interface Wireguard { export const wireguard: Wireguard = { generateKeypair: function () { - const privateKey = generatePrivateKey(); - const publicKey = generatePublicKey(privateKey); - + const [privateKeyOk, privateKey] = pcall<[], number[]>(() => generatePrivateKey()); + const [publicKeyOk, publicKey] = privateKeyOk + ? pcall<[], number[]>(() => generatePublicKey(privateKey)) + : error("failed to generate private key"); return { - publicKey: atob(publicKey), - privateKey: atob(privateKey), + publicKey: atob(publicKeyOk ? publicKey : error("failed to generate public key")), + privateKey: atob(privateKey as number[]), }; }, generatePublicKey: function (privateKey) { - return atob(generatePublicKey(privateKey)); + const [publicKeyOk, publicKey] = pcall<[], number[]>(() => generatePublicKey(privateKey)); + + return atob(publicKeyOk ? publicKey : error("failed to generate public key")); }, };