add error helper class

This commit is contained in:
rafiarrafif
2025-05-10 01:23:07 +07:00
parent 83f30bd36c
commit 954d40df3b
3 changed files with 24 additions and 3 deletions

View File

@ -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);
}
}

View File

@ -3,6 +3,7 @@ import { loginWithPasswordService } from "../services/loginWithPassword.service"
import { loginWithPasswordSchema } from "../auth.schema"; import { loginWithPasswordSchema } from "../auth.schema";
import { returnErrorResponse } from "../../../helpers/callback/httpResponse"; import { returnErrorResponse } from "../../../helpers/callback/httpResponse";
import { LoginWithPasswordRequest } from "../auth.types"; import { LoginWithPasswordRequest } from "../auth.types";
import { AppError } from "../../../helpers/error/handler";
export const loginWithPassword = async ( export const loginWithPassword = async (
ctx: Context & { body: LoginWithPasswordRequest } ctx: Context & { body: LoginWithPasswordRequest }
@ -15,6 +16,13 @@ export const loginWithPassword = async (
const result = await loginWithPasswordService(ctx.body); const result = await loginWithPasswordService(ctx.body);
return result; return result;
} catch (error) { } catch (error) {
return error; if (error instanceof AppError) {
return returnErrorResponse(
ctx.set,
error.statusCode,
error.message,
error.details
);
}
} }
}; };

View File

@ -1,3 +1,4 @@
import { AppError } from "../../../helpers/error/handler";
import { userModel } from "../user.model"; import { userModel } from "../user.model";
export const findUserByEmailOrUsernameRepo = async (identifier: string) => { 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; return userData;
}; };