【问题标题】:Send message with actionresult发送带有 actionresult 的消息
【发布时间】:2019-08-12 06:05:39
【问题描述】:

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

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

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

当前实现

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

这在邮递员中返回一个空响应,错误为 500

【问题讨论】:

    标签: c# exception error-handling azure-functions


    【解决方案1】:

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

    例如:

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

    你也可以传递一个对象(例如使用HttpStatusCode枚举):

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

    【讨论】:

    • StatusCodeResponse 没有带 2 个参数的构造函数。
    • @AramKocharyan 你是对的,我写答案时的错误。我已经更新了我的答案
    • StatusCode 是在ControllerBase 中定义的函数。 OP 正在询问 Azure Functions。顺便说一句,StatusCode 再次没有 2 个参数的重载。
    • @AramKocharyan 它肯定在 asp.net 核心中。 You can check here,虽然不确定 azure 函数
    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-01-08
      • 2015-10-16
      • 2017-02-01
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2018-09-21
      相关资源
      最近更新 更多