Created
August 19, 2023 01:03
-
-
Save mykeels/1110a1a4ba68baf9de71236ba0a9eb9d to your computer and use it in GitHub Desktop.
controller-error-handling.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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