import Knex from 'knex'; export type EndpointHandler = (req: any, res: any, knex: Knex) => Promise; export interface EndpointError extends Error { name: "EndpointError", message: string; httpStatus: Number; } export enum DBErrorKind { Unknown = "Unknown", ResourceNotFound = "ResourceNotFound", ResourceConflict = "ResourceConflict", } export interface DBError extends Error { name: "DBError", kind: DBErrorKind, message: string, } export function isEndpointError(obj: any): obj is EndpointError { return obj.name === "EndpointError"; } export function isDBError(obj: any): obj is DBError { return obj.name === "DBError"; } export function toEndpointError(e: Error): EndpointError { if (isEndpointError(e)) { return e; } else if (isDBError(e) && e.kind === DBErrorKind.ResourceNotFound) { return { name: "EndpointError", message: e.message, httpStatus: 404, } } else if (isDBError(e) && e.kind === DBErrorKind.ResourceConflict) { return { name: "EndpointError", message: e.message, httpStatus: 409, } } return { name: "EndpointError", message: e.message, httpStatus: 500, } } export const handleErrorsInEndpoint = (_e: any) => { throw toEndpointError(_e); }