@httpc/kit
Version:
httpc toolbox for building function-based API with minimal code and end-to-end type safety
48 lines (47 loc) • 1.49 kB
JavaScript
import { ForbiddenError, isErrorOf, NotFoundError, UnauthorizedError } from "@httpc/server";
import { useLogger } from "../logging";
export function catchError(error, func) {
return (err) => {
if (isErrorOf(typeof error === "string" ? error : undefined, typeof error === "string" ? undefined : error, err)) {
return func?.(err);
}
throw err;
};
}
export function catchNotFound(func) {
return (err) => {
if (isErrorOf("not_found", NotFoundError, err)) {
return func(err);
}
throw err;
};
}
export function catchNotFoundThrows(error) {
return (err) => {
if (isErrorOf("not_found", NotFoundError, err)) {
throw error();
}
throw err;
};
}
export function catchNotFoundThrowUnauthorized(message) {
return catchNotFoundThrows(() => new UnauthorizedError(message));
}
export function catchNotFoundThrowForbidden(message) {
return catchNotFoundThrows(() => new ForbiddenError(message));
}
export function catchNotFoundThrowNotFound(message) {
return catchNotFoundThrows(() => new NotFoundError(message));
}
export function catchLogAndThrowUnauthorized(log, message) {
return (err) => {
const logger = useLogger();
if (log) {
logger.error(log, err);
}
else {
logger.error(err);
}
throw new UnauthorizedError(message);
};
}