import { BadRequestException } from '@nestjs/common'; export type Result = { result?: T; error?: E; }; export function success(res: T): Result { return { result: res, }; } export function fail(error: E): Result { return { error: error, }; } export function getOrThrow(res: Result): T { if (res.result) return res.result; throw res.error ? res.error : 'UNKNOWN_ERROR'; } export async function successOrError( cb: () => Promise, ): Promise> { try { const res = await cb(); return { result: res, }; } catch (ex) { return { error: ex, }; } } export type AppError = Error & { app: true; }; export function createAppError(msg: string | Error): AppError { let err: any; if (typeof msg === 'string') { err = new Error(msg); } else if (typeof msg === 'object') { err = msg; } else { err = new Error('UNKNOWN_APP_ERROR'); } err.name = 'ApplicationError'; return err; } export async function getOrAppErrorOrThrow( fn: () => Promise, onAppError?: (err: Error) => Error, onOtherError?: (err: Error) => Error, ): Promise { try { return await fn(); } catch (ex) { if (ex && ex.name === 'ApplicationError') { throw onAppError ? onAppError(ex) : ex; } throw onOtherError ? onOtherError(ex) : ex; } } export function BadRequestErrorHandler(err: Error): Error { return new BadRequestException(err.message); }