Fix error handling of DittoRoute

This commit is contained in:
Alex Gleason 2025-03-03 15:41:24 -06:00
parent b8b6174fcc
commit bcd2ed18ef
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7
2 changed files with 25 additions and 3 deletions

View file

@ -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);
});

View file

@ -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<DittoEnv> {
this.assertVars(c.var);
return next();
});
this.onError(this._errorHandler);
}
private assertVars(vars: Partial<DittoEnv['Variables']>): DittoEnv['Variables'] {
@ -38,4 +40,16 @@ export class DittoRoute extends Hono<DittoEnv> {
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;
};
}