feat: improve structure and error handling

This commit is contained in:
Michael Zetterberg
2024-05-14 15:55:46 +02:00
parent 01587d7fd5
commit f5108d1a8e
104 changed files with 1505 additions and 1570 deletions

View File

@@ -3,6 +3,20 @@ import { NextResponse } from "next/server"
export function badRequest(body: unknown | string = "Bad request") {
const resInit = {
status: 400,
statusText: "Bad request",
}
if (typeof body === "string") {
return new NextResponse(body, resInit)
}
return NextResponse.json(body, resInit)
}
export function notFound(body: unknown | string = "Not found") {
const resInit = {
status: 404,
statusText: "Not found",
}
if (typeof body === "string") {
@@ -17,6 +31,7 @@ export function internalServerError(
) {
const resInit = {
status: 500,
statusText: "Internal Server Error",
}
if (typeof body === "string") {

View File

@@ -1,35 +1,41 @@
import { TRPCError } from "@trpc/server"
import {
TRPC_ERROR_CODES_BY_KEY,
TRPC_ERROR_CODES_BY_NUMBER,
} from "@trpc/server/rpc"
export function unauthorizedError() {
export function unauthorizedError(cause?: unknown) {
return new TRPCError({
code: TRPC_ERROR_CODES_BY_NUMBER[TRPC_ERROR_CODES_BY_KEY.UNAUTHORIZED],
message: `Authorization required!`,
code: "UNAUTHORIZED",
message: `Unauthorized`,
cause,
})
}
export function forbiddenError() {
export function forbiddenError(cause?: unknown) {
return new TRPCError({
code: TRPC_ERROR_CODES_BY_NUMBER[TRPC_ERROR_CODES_BY_KEY.FORBIDDEN],
message: `You do not have permission!`,
code: "FORBIDDEN",
message: `Forbidden`,
cause,
})
}
export function badRequestError(msg = "Bad request!") {
export function badRequestError(cause?: unknown) {
return new TRPCError({
code: TRPC_ERROR_CODES_BY_NUMBER[TRPC_ERROR_CODES_BY_KEY.BAD_REQUEST],
message: msg,
code: "BAD_REQUEST",
message: `Bad request`,
cause,
})
}
export function internalServerError() {
export function notFound(cause?: unknown) {
return new TRPCError({
code: TRPC_ERROR_CODES_BY_NUMBER[
TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR
],
message: `Internal Server Error!`,
code: "NOT_FOUND",
message: `Not found`,
cause,
})
}
export function internalServerError(cause?: unknown) {
return new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: `Internal Server Error`,
cause,
})
}