From 715de6b70d25b10e8d67eb0a3f20628adcc9f601 Mon Sep 17 00:00:00 2001 From: mbaharip <62494292+mbahArip@users.noreply.github.com> Date: Sun, 7 Apr 2024 12:02:25 +0700 Subject: [PATCH] Add proper error handling --- src/utils/encryptionHelper/hash.ts | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/utils/encryptionHelper/hash.ts b/src/utils/encryptionHelper/hash.ts index 436ae16..8025133 100644 --- a/src/utils/encryptionHelper/hash.ts +++ b/src/utils/encryptionHelper/hash.ts @@ -17,10 +17,17 @@ const key = generateKey(); const iv = Buffer.from(key); export async function encryptData(data: string): Promise { - const cipher = crypto.createCipheriv("aes-128-cbc", key, iv); - return Buffer.concat([cipher.update(data, "utf-8"), cipher.final()]).toString( - "hex", - ); + try { + const cipher = crypto.createCipheriv("aes-128-cbc", key, iv); + return Buffer.concat([ + cipher.update(data, "utf-8"), + cipher.final(), + ]).toString("hex"); + } catch (error) { + const e = error as Error; + console.error(e.message); + throw new Error(e.message); + } } export async function decryptData(hash: string): Promise { @@ -32,6 +39,10 @@ export async function decryptData(hash: string): Promise { decipher.final(), ]).toString("utf-8"); } catch (error) { - return ""; + const e = error as Error; + console.error(e.message); + throw new Error( + "Failed to decrypt data, either invalid hash or encryption key.", + ); } }