22using ByteSync . ServerCommon . Exceptions ;
33using Microsoft . ApplicationInsights ;
44using Microsoft . Azure . Functions . Worker ;
5+ using Microsoft . Azure . Functions . Worker . Http ;
56using Microsoft . Azure . Functions . Worker . Middleware ;
67using Microsoft . Extensions . Logging ;
78
@@ -24,6 +25,20 @@ public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next
2425 {
2526 await next ( context ) ;
2627 }
28+ catch ( BadRequestException ex )
29+ {
30+ _telemetryClient . TrackException ( ex ) ;
31+ _logger . LogWarning ( ex , "An error occurred in function {FunctionName}" , context . FunctionDefinition . Name ) ;
32+
33+ var httpRequest = await context . GetHttpRequestDataAsync ( ) ;
34+ if ( httpRequest != null )
35+ {
36+ PrepareResponse ( context , httpRequest , HttpStatusCode . BadRequest ) ;
37+
38+ return ;
39+ }
40+ throw ;
41+ }
2742 catch ( Exception ex )
2843 {
2944 _telemetryClient . TrackException ( ex ) ;
@@ -32,22 +47,18 @@ public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next
3247 var httpRequest = await context . GetHttpRequestDataAsync ( ) ;
3348 if ( httpRequest != null )
3449 {
35- var response = httpRequest . CreateResponse ( ) ;
50+ PrepareResponse ( context , httpRequest , HttpStatusCode . InternalServerError ) ;
3651
37- if ( ex is BadRequestException )
38- {
39- response . StatusCode = HttpStatusCode . BadRequest ;
40- }
41- else
42- {
43- response . StatusCode = HttpStatusCode . InternalServerError ;
44- }
45-
46- context . GetInvocationResult ( ) . Value = response ;
47-
4852 return ;
4953 }
5054 throw ;
5155 }
5256 }
57+
58+ private static void PrepareResponse ( FunctionContext context , HttpRequestData httpRequest , HttpStatusCode statusCode )
59+ {
60+ var response = httpRequest . CreateResponse ( ) ;
61+ response . StatusCode = statusCode ;
62+ context . GetInvocationResult ( ) . Value = response ;
63+ }
5364}
0 commit comments