Skip to content

Commit 246510f

Browse files
committed
allowed throwing of built in errors from the error handler
1 parent f939795 commit 246510f

File tree

3 files changed

+46
-5
lines changed

3 files changed

+46
-5
lines changed

packages/event-handler/src/rest/Router.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,12 @@ class Router {
331331
headers: { 'Content-Type': 'application/json' },
332332
});
333333
} catch (handlerError) {
334+
if (handlerError instanceof NotFoundError) {
335+
return await this.handleError(handlerError, options);
336+
}
337+
if (handlerError instanceof MethodNotAllowedError) {
338+
return await this.handleError(handlerError, options);
339+
}
334340
return this.#defaultErrorHandler(handlerError as Error);
335341
}
336342
}

packages/event-handler/src/types/rest.ts

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,17 @@ import type { Route } from '../rest/Route.js';
1212
import type { Router } from '../rest/Router.js';
1313
import type { ResolveOptions } from './common.js';
1414

15-
type ErrorResponse = {
16-
statusCode: HttpStatusCode;
17-
error: string;
18-
message: string;
19-
};
15+
type ErrorResponse =
16+
| {
17+
statusCode: HttpStatusCode;
18+
error: string;
19+
message?: string;
20+
}
21+
| {
22+
statusCode: HttpStatusCode;
23+
error?: string;
24+
message: string;
25+
};
2026

2127
type RequestContext = {
2228
req: Request;

packages/event-handler/tests/unit/rest/Router/error-handling.test.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
HttpErrorCodes,
66
InternalServerError,
77
MethodNotAllowedError,
8+
NotFoundError,
89
Router,
910
} from '../../../../src/rest/index.js';
1011
import { createTestEvent } from '../helpers.js';
@@ -429,4 +430,32 @@ describe('Class: Router - Error Handling', () => {
429430
isBase64Encoded: false,
430431
});
431432
});
433+
434+
it('handles throwing a built in error from the error handler', async () => {
435+
// Prepare
436+
const app = new Router();
437+
438+
app.errorHandler(BadRequestError, async () => {
439+
throw new NotFoundError('This error is thrown from the error handler');
440+
});
441+
442+
app.get('/test', () => {
443+
throw new BadRequestError('test error');
444+
});
445+
446+
// Act
447+
const result = await app.resolve(createTestEvent('/test', 'GET'), context);
448+
449+
// Assess
450+
expect(result).toEqual({
451+
statusCode: HttpErrorCodes.NOT_FOUND,
452+
body: JSON.stringify({
453+
statusCode: HttpErrorCodes.NOT_FOUND,
454+
error: 'NotFoundError',
455+
message: 'This error is thrown from the error handler',
456+
}),
457+
headers: { 'content-type': 'application/json' },
458+
isBase64Encoded: false,
459+
});
460+
});
432461
});

0 commit comments

Comments
 (0)