Search code examples
c#.netazure-functionsresponsestatus

return badrequest with message using Azure Isolated functions


I have an Azure (Isolated) Functions app and I'm trying to handle unexpected exceptions when they're threw. Actually I need to catch generic Exception for those unexpected ones, but when I return them I get some noise that I don't want to show.

        [Function("ExceptionTest")]
        public async Task<ActionResult> ExceptionTest([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
        {
            try
            {
                throw new NotImplementedException();
            }
            catch (Exception ex)
            {
                return new BadRequestObjectResult(ex.Message);
            }
        }

There are two main issues, the first one is that body response says "400 status code", but Postman shows 200 status code.

The second one is that I can't find any way to remove the formatters, contenttypes, declaredtypes and statusCode in the response.

{
  "Value": "The method or operation is not implemented.",
  "Formatters": [],
  "ContentTypes": [],
  "DeclaredType": null,
  "StatusCode": 400
}

This started happening when we implemented Azure Isolated functions. It does not happen in normal functions.

How am I supposed to return or handle exceptions? Either unexpected or exceptions produced in code, e.g. UnauthorizedAccessException, without returning that much noise.


Solution

  • I finally managed to solve it in the following way, it was simpler than I expected.

    catch (UnauthorizedAccessException ex)
    {
                    
        var error = req.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
        error.WriteString(ex.Message);
        return error;
    }
    

    This way you receive the correct error code and can handle it correctly.