Skip to content

Commit ea448b1

Browse files
committed
allowed returning JSONObject from error handler
1 parent 3102fef commit ea448b1

File tree

3 files changed

+31
-7
lines changed

3 files changed

+31
-7
lines changed

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

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -327,14 +327,11 @@ class Router {
327327
}
328328
}
329329
return new Response(JSON.stringify(body), {
330-
status: body.statusCode,
330+
status: (body.statusCode as number) ?? HttpErrorCodes.OK,
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) {
334+
if (handlerError instanceof ServiceError) {
338335
return await this.handleError(handlerError, options);
339336
}
340337
return this.#defaultErrorHandler(handlerError as Error);

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,11 @@ type ErrorHandler<T extends Error = Error> = T extends
4040
? (
4141
error: T,
4242
reqCtx: RequestContext
43-
) => Promise<Omit<ErrorResponse, 'statusCode'> | Response>
44-
: (error: T, reqCtx: RequestContext) => Promise<ErrorResponse | Response>;
43+
) => Promise<Omit<ErrorResponse, 'statusCode'> | Response | JSONObject>
44+
: (
45+
error: T,
46+
reqCtx: RequestContext
47+
) => Promise<ErrorResponse | Response | JSONObject>;
4548

4649
interface ErrorConstructor<T extends Error = Error> {
4750
new (...args: any[]): T;

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,30 @@ describe('Class: Router - Error Handling', () => {
431431
});
432432
});
433433

434+
it('handles returning a JSONObject from the error handler', async () => {
435+
// Prepare
436+
const app = new Router();
437+
438+
app.errorHandler(BadRequestError, async () => ({ foo: 'bar' }));
439+
440+
app.get('/test', () => {
441+
throw new BadRequestError('test error');
442+
});
443+
444+
// Act
445+
const result = await app.resolve(createTestEvent('/test', 'GET'), context);
446+
447+
// Assess
448+
expect(result).toEqual({
449+
statusCode: HttpErrorCodes.OK,
450+
body: JSON.stringify({
451+
foo: 'bar',
452+
}),
453+
headers: { 'content-type': 'application/json' },
454+
isBase64Encoded: false,
455+
});
456+
});
457+
434458
it('handles throwing a built in NotFound error from the error handler', async () => {
435459
// Prepare
436460
const app = new Router();

0 commit comments

Comments
 (0)