@@ -4,7 +4,11 @@ import {
4
4
isDevMode ,
5
5
} from '@aws-lambda-powertools/commons/utils/env' ;
6
6
import type { APIGatewayProxyResult , Context } from 'aws-lambda' ;
7
- import type { ResolveOptions } from '../types/index.js' ;
7
+ import type {
8
+ HandlerResponse ,
9
+ HttpStatusCode ,
10
+ ResolveOptions ,
11
+ } from '../types/index.js' ;
8
12
import type {
9
13
ErrorConstructor ,
10
14
ErrorHandler ,
@@ -22,7 +26,6 @@ import {
22
26
handlerResultToProxyResult ,
23
27
handlerResultToWebResponse ,
24
28
proxyEventToWebRequest ,
25
- webResponseToProxyResult ,
26
29
} from './converters.js' ;
27
30
import { ErrorHandlerRegistry } from './ErrorHandlerRegistry.js' ;
28
31
import {
@@ -36,6 +39,7 @@ import { RouteHandlerRegistry } from './RouteHandlerRegistry.js';
36
39
import {
37
40
composeMiddleware ,
38
41
isAPIGatewayProxyEvent ,
42
+ isAPIGatewayProxyResult ,
39
43
isHttpMethod ,
40
44
} from './utils.js' ;
41
45
@@ -280,7 +284,9 @@ class Router {
280
284
...requestContext ,
281
285
scope : options ?. scope ,
282
286
} ) ;
283
- return await webResponseToProxyResult ( result ) ;
287
+ const statusCode =
288
+ result instanceof Response ? result . status : result . statusCode ;
289
+ return handlerResultToProxyResult ( result , statusCode as HttpStatusCode ) ;
284
290
}
285
291
}
286
292
@@ -310,17 +316,31 @@ class Router {
310
316
protected async handleError (
311
317
error : Error ,
312
318
options : ErrorResolveOptions
313
- ) : Promise < Response > {
319
+ ) : Promise < HandlerResponse > {
314
320
const handler = this . errorHandlerRegistry . resolve ( error ) ;
315
321
if ( handler !== null ) {
316
322
try {
317
323
const { scope, ...reqCtx } = options ;
318
324
const body = await handler . apply ( scope ?? this , [ error , reqCtx ] ) ;
325
+ if ( body instanceof Response || isAPIGatewayProxyResult ( body ) ) {
326
+ return body ;
327
+ }
328
+ if ( ! body . statusCode ) {
329
+ if ( error instanceof NotFoundError ) {
330
+ body . statusCode = HttpErrorCodes . NOT_FOUND ;
331
+ } else if ( error instanceof MethodNotAllowedError ) {
332
+ body . statusCode = HttpErrorCodes . METHOD_NOT_ALLOWED ;
333
+ }
334
+ }
319
335
return new Response ( JSON . stringify ( body ) , {
320
- status : body . statusCode ,
336
+ status :
337
+ ( body . statusCode as number ) ?? HttpErrorCodes . INTERNAL_SERVER_ERROR ,
321
338
headers : { 'Content-Type' : 'application/json' } ,
322
339
} ) ;
323
340
} catch ( handlerError ) {
341
+ if ( handlerError instanceof ServiceError ) {
342
+ return await this . handleError ( handlerError , options ) ;
343
+ }
324
344
return this . #defaultErrorHandler( handlerError as Error ) ;
325
345
}
326
346
}
0 commit comments