From bcd2ed18efb744bf2f877f1e1049adad8dea2f16 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 3 Mar 2025 15:41:24 -0600 Subject: [PATCH] Fix error handling of DittoRoute --- packages/mastoapi/router/DittoApp.test.ts | 12 ++++++++++-- packages/mastoapi/router/DittoRoute.ts | 16 +++++++++++++++- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/packages/mastoapi/router/DittoApp.test.ts b/packages/mastoapi/router/DittoApp.test.ts index c828d68a..f4a2bd44 100644 --- a/packages/mastoapi/router/DittoApp.test.ts +++ b/packages/mastoapi/router/DittoApp.test.ts @@ -1,13 +1,14 @@ import { DittoConf } from '@ditto/conf'; -import { DittoPolyPg } from '@ditto/db'; +import { DummyDB } from '@ditto/db'; import { Hono } from '@hono/hono'; import { MockRelay } from '@nostrify/nostrify/test'; +import { assertEquals } from '@std/assert'; import { DittoApp } from './DittoApp.ts'; import { DittoRoute } from './DittoRoute.ts'; Deno.test('DittoApp', async () => { - await using db = new DittoPolyPg('memory://'); + await using db = new DummyDB(); const conf = new DittoConf(new Map()); const relay = new MockRelay(); @@ -20,4 +21,11 @@ Deno.test('DittoApp', async () => { // @ts-expect-error Passing a non-DittoRoute to route. app.route('/', hono); + + app.get('/error', () => { + throw new Error('test error'); + }); + + const response = await app.request('/error'); + assertEquals(response.status, 500); }); diff --git a/packages/mastoapi/router/DittoRoute.ts b/packages/mastoapi/router/DittoRoute.ts index a4803b6e..4c78c4b3 100644 --- a/packages/mastoapi/router/DittoRoute.ts +++ b/packages/mastoapi/router/DittoRoute.ts @@ -1,4 +1,4 @@ -import { Hono } from '@hono/hono'; +import { type ErrorHandler, Hono } from '@hono/hono'; import { HTTPException } from '@hono/hono/http-exception'; import type { HonoOptions } from '@hono/hono/hono-base'; @@ -16,6 +16,8 @@ export class DittoRoute extends Hono { this.assertVars(c.var); return next(); }); + + this.onError(this._errorHandler); } private assertVars(vars: Partial): DittoEnv['Variables'] { @@ -38,4 +40,16 @@ export class DittoRoute extends Hono { private throwMissingVar(name: string): never { throw new HTTPException(500, { message: `Missing required variable: ${name}` }); } + + private _errorHandler: ErrorHandler = (error, c) => { + if (error instanceof HTTPException) { + if (error.res) { + return error.res; + } else { + return c.json({ error: error.message }, error.status); + } + } + + throw error; + }; }