From 954d40df3b209c72d1e00c2ea0ca543031462c6e Mon Sep 17 00:00:00 2001 From: rafiarrafif Date: Sat, 10 May 2025 01:23:07 +0700 Subject: [PATCH] add error helper class --- src/helpers/error/handler/index.ts | 13 +++++++++++++ .../auth/controller/loginWithPassword.controller.ts | 10 +++++++++- .../findUserByEmailOrUsername.repository.ts | 4 ++-- 3 files changed, 24 insertions(+), 3 deletions(-) create mode 100644 src/helpers/error/handler/index.ts diff --git a/src/helpers/error/handler/index.ts b/src/helpers/error/handler/index.ts new file mode 100644 index 0000000..0d80636 --- /dev/null +++ b/src/helpers/error/handler/index.ts @@ -0,0 +1,13 @@ +export class AppError extends Error { + public readonly statusCode: number; + public readonly details?: any; + + constructor(statusCode = 400, message: string, details?: any) { + super(message); + this.name = "AppError"; + this.statusCode = statusCode; + this.details = details; + + Object.setPrototypeOf(this, AppError.prototype); + } +} diff --git a/src/modules/auth/controller/loginWithPassword.controller.ts b/src/modules/auth/controller/loginWithPassword.controller.ts index 595947b..f415d36 100644 --- a/src/modules/auth/controller/loginWithPassword.controller.ts +++ b/src/modules/auth/controller/loginWithPassword.controller.ts @@ -3,6 +3,7 @@ import { loginWithPasswordService } from "../services/loginWithPassword.service" import { loginWithPasswordSchema } from "../auth.schema"; import { returnErrorResponse } from "../../../helpers/callback/httpResponse"; import { LoginWithPasswordRequest } from "../auth.types"; +import { AppError } from "../../../helpers/error/handler"; export const loginWithPassword = async ( ctx: Context & { body: LoginWithPasswordRequest } @@ -15,6 +16,13 @@ export const loginWithPassword = async ( const result = await loginWithPasswordService(ctx.body); return result; } catch (error) { - return error; + if (error instanceof AppError) { + return returnErrorResponse( + ctx.set, + error.statusCode, + error.message, + error.details + ); + } } }; diff --git a/src/modules/user/repositories/findUserByEmailOrUsername.repository.ts b/src/modules/user/repositories/findUserByEmailOrUsername.repository.ts index 66fb782..5dce67e 100644 --- a/src/modules/user/repositories/findUserByEmailOrUsername.repository.ts +++ b/src/modules/user/repositories/findUserByEmailOrUsername.repository.ts @@ -1,3 +1,4 @@ +import { AppError } from "../../../helpers/error/handler"; import { userModel } from "../user.model"; export const findUserByEmailOrUsernameRepo = async (identifier: string) => { @@ -29,7 +30,6 @@ export const findUserByEmailOrUsernameRepo = async (identifier: string) => { }, })); - if (!userData) throw "User not found"; - + if (!userData) throw new AppError(404, "User not exist"); return userData; };