Skip to content

Commit 534c1f2

Browse files
committed
feat: improve error handling
1 parent dafc505 commit 534c1f2

File tree

1 file changed

+23
-12
lines changed

1 file changed

+23
-12
lines changed

src/ByteSync.Functions/Helpers/Middlewares/ErrorHandlingMiddleware.cs

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using ByteSync.ServerCommon.Exceptions;
33
using Microsoft.ApplicationInsights;
44
using Microsoft.Azure.Functions.Worker;
5+
using Microsoft.Azure.Functions.Worker.Http;
56
using Microsoft.Azure.Functions.Worker.Middleware;
67
using 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

Comments
 (0)