title: Azure Function Middleware: How to return a custom HTTP response?
body: <p>I am exploring Azure Function running on <code>.net 5</code> and I found out about the new <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.middlewareworkerapplicationbuilderextensions.usemiddleware?view=azure-dotnet" rel="noreferrer">middleware capabilities</a>.</p>
  <p>I have built a dummy middleware like this one:</p>
  <pre><code>public sealed class ExceptionLoggingMiddleware : IFunctionsWorkerMiddleware
  {
      private readonly ILogger&lt;ExceptionLoggingMiddleware&gt; m_logger;
  
      public ExceptionLoggingMiddleware(ILogger&lt;ExceptionLoggingMiddleware&gt; logger)
      {
          m_logger = logger;
      }
  
      public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
      {
          try
          {
              await next(context);
          }
          catch (Exception unhandledException)
          {
              m_logger.LogCritical(unhandledException, &quot;Unhandled exception caught: {UnhandledException}&quot;, unhandledException.Message);
          }
      }
  }
  </code></pre>
  <p>In my use case, the Azure Function is an HTTP triggered function:</p>
  <pre><code>public sealed class StorageAccountsFunction
  {
      private readonly ILogger&lt;StorageAccountsFunction&gt; m_logger;
  
      public StorageAccountsFunction
      (
          ILogger&lt;StorageAccountsFunction&gt; logger
      )
      {
          m_logger = logger;
      }
  
      [Function(&quot;v1-post-storage-account&quot;)]
      public async Task&lt;HttpResponseData&gt; CreateAsync
      (
          [HttpTrigger(AuthorizationLevel.Anonymous, &quot;POST&quot;, Route = &quot;v1/storage-accounts&quot;)] 
          HttpRequestData httpRequestData, 
          FunctionContext context
      )
      {
          m_logger.LogInformation(&quot;Processing a request to create a new storage account&quot;);
  
          throw new Exception(&quot;Oh no! Oh well..&quot;);
      }
  }
  </code></pre>
  <p>In my Function App running in-process on <code>.net core 3.1</code>, each Function had the responsibility of catching the unhandled exception (via a base class) and returned the appropriate HTTP status code.</p>
  <p>I would like to have that logic sit in a middleware instead to have it centralized and avoid any future mistakes.</p>
  <p><strong>Question</strong></p>
  <p>The exception is caught by the middleware properly. However, I do not see how I can alter the response and return something more appropriate, instead of a <code>500 Internal Server Error</code> that I get right now?</p>