使用actionresult发送消息

问题描述 投票:1回答:2

我需要从azure函数返回服务器错误。

现在我使用InternalServerErrorResult()实现相同的功能。它只发送错误代码,并且不能使用此功能发送响应/消息。

如何实现异常处理程序,其中错误代码和消息可以在azure函数中使用actionresult一起发送

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();
            }

这会在postman中返回一个空响应,错误为500

c# exception error-handling azure-functions
2个回答
2
投票

请注意,这是来自Microsoft.AspNetCore.Mvc命名空间:

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

基于配置的格式化程序,它将序列化对象返回给客户端。对于JSON(它是默认值),它将返回以下内容:

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

0
投票

要发送带有状态代码的消息,您可以使用return StatusCode(httpCode, message),这是一个ObjectResult

例如:

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

您还可以传递一个对象(使用HttpStatusCode枚举的示例):

return StatusCode((int)HttpStatusCode.InternalServerError, json);
© www.soinside.com 2019 - 2024. All rights reserved.