Reputation: 22769
In a C# Azure function what Exception classes can be thrown to cause specific HTTP status codes to be returned from the API. For example a "404 Not Found" when a key lookup in an in-memory structure has no hits.
I would like to avoid returning codes up the stack when we have exceptions available that were created for this purpose.
Upvotes: 2
Views: 1050
Reputation: 7927
There appears to be two ways to do this, however, one is in preview.
Preview:
https://github.com/Azure/azure-webjobs-sdk/wiki/Function-Filters
Middlware:
If you run your Azure function as an isolated process you can add your own custom middleware which could take care of exception handling.
https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide#middleware
// Source above
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults(workerApplication =>
{
// Register our custom middlewares with the worker
workerApplication.UseMiddleware<ExceptionHandlingMiddleware>();
workerApplication.UseMiddleware<MyCustomMiddleware>();
workerApplication.UseWhen<StampHttpHeaderMiddleware>((context) =>
{
// We want to use this middleware only for http trigger invocations.
return context.FunctionDefinition.InputBindings.Values
.First(a => a.Type.EndsWith("Trigger")).Type == "httpTrigger";
});
})
.Build();
In doing so you would need to then return HttpResponseData object.
Upvotes: 1