Skip to content

Instantly share code, notes, and snippets.

@mykeels
Created August 19, 2023 01:03
Show Gist options
  • Save mykeels/1110a1a4ba68baf9de71236ba0a9eb9d to your computer and use it in GitHub Desktop.
Save mykeels/1110a1a4ba68baf9de71236ba0a9eb9d to your computer and use it in GitHub Desktop.
controller-error-handling.ts
import httpStatus from "http-status";
export const makeError = <TErrorName extends string>(
name: TErrorName,
message?: string
) => ({
name,
message,
});
interface ControllerErrorHandler {
handle: (error: unknown) => ControllerError;
}
export interface ControllerError {
error: { name: string };
}
export const mapErrors = (
mapping: Record<string, number>,
context: { setStatus: (code: number) => void }
): ControllerErrorHandler => {
mapping = {
...mapping,
ZodError: httpStatus.BAD_REQUEST,
};
return {
handle: (error: unknown) => {
console.error(error);
const name =
error &&
typeof error === "object" &&
"name" in error &&
typeof error.name === "string" &&
error.name in mapping
? error.name
: "Unknown";
const code =
(!error ? httpStatus.INTERNAL_SERVER_ERROR : mapping[name]) ||
httpStatus.INTERNAL_SERVER_ERROR;
context.setStatus(code);
return {
error: {
name,
},
};
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment