Sanjeev S
Sanjeev S

Reputation: 1163

Send message with actionresult

I need to return the server error from azure functions.

Now I implement the same using InternalServerErrorResult(). It only sends the error code and no response/message can be sent with this function.

How to implement an exception handler where the error code and message can be sent together using actionresult in azure functions

current implementation

catch (Exception ex)
            {
                log.LogInformation("An error occured {0}" + ex);
                //json = new Response(ex.StackTrace, AppConstants.ErrorCodes.SystemException).SerializeToString();
                return (ActionResult)new InternalServerErrorResult();
            }

this returns with an empty response in postman with error 500

Upvotes: 4

Views: 4267

Answers (2)

haldo
haldo

Reputation: 16711

To send a message with the status code you can use return StatusCode(httpCode, message), which is an ObjectResult.

For example:

return StatusCode(500, "An error occurred");

You can also pass an object (example using HttpStatusCode enum):

return StatusCode((int)HttpStatusCode.InternalServerError, json);

Upvotes: 0

bot_insane
bot_insane

Reputation: 2604

Note that this is from Microsoft.AspNetCore.Mvc namespace:

var result = new ObjectResult(new { error = "your error message here" })
{
    StatusCode = 500
};

Based on configured formatters it will return serialized object to client. For JSON (it's default) it will return following:

{ "error" : "your error message here" }

Upvotes: 7

Related Questions