refactor(api): ♻️ Throw ApiError instead of returning error JSON

This commit is contained in:
Jesse Wierzbinski 2024-12-30 18:00:23 +01:00
parent c14621ee06
commit fbfd237f27
No known key found for this signature in database
88 changed files with 458 additions and 483 deletions

View file

@ -1,4 +1,5 @@
import { createMiddleware } from "hono/factory";
import { ApiError } from "~/classes/errors/api-error";
import { config } from "~/packages/config-manager";
export const agentBans = createMiddleware(async (context, next) => {
@ -7,7 +8,7 @@ export const agentBans = createMiddleware(async (context, next) => {
for (const agent of config.http.banned_user_agents) {
if (new RegExp(agent).test(ua)) {
return context.json({ error: "Forbidden" }, 403);
throw new ApiError(403, "Forbidden");
}
}

View file

@ -1,4 +1,5 @@
import { createMiddleware } from "hono/factory";
import { ApiError } from "~/classes/errors/api-error";
export const boundaryCheck = createMiddleware(async (context, next) => {
// Checks that FormData boundary is present
@ -6,11 +7,10 @@ export const boundaryCheck = createMiddleware(async (context, next) => {
if (contentType?.includes("multipart/form-data")) {
if (!contentType.includes("boundary")) {
return context.json(
{
error: "You are sending a request with a multipart/form-data content type but without a boundary. Please include a boundary in the Content-Type header. For more information, visit https://stackoverflow.com/questions/3508338/what-is-the-boundary-in-multipart-form-data",
},
throw new ApiError(
400,
"Missing FormData boundary",
"You are sending a request with a multipart/form-data content type but without a boundary. Please include a boundary in the Content-Type header. For more information, visit https://stackoverflow.com/questions/3508338/what-is-the-boundary-in-multipart-form-data",
);
}
}

View file

@ -3,6 +3,7 @@ import { getLogger } from "@logtape/logtape";
import type { SocketAddress } from "bun";
import { createMiddleware } from "hono/factory";
import { matches } from "ip-matching";
import { ApiError } from "~/classes/errors/api-error";
import { config } from "~/packages/config-manager";
export const ipBans = createMiddleware(async (context, next) => {
@ -18,7 +19,7 @@ export const ipBans = createMiddleware(async (context, next) => {
for (const ip of config.http.banned_ips) {
try {
if (matches(ip, requestIp?.address)) {
return context.json({ error: "Forbidden" }, 403);
throw new ApiError(403, "Forbidden");
}
} catch (e) {
const logger = getLogger("server");