如何从 .NET 中的 RESTful 响应中获取内部异常消息?

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

有一个请求失败,错误消息显示

Response (Uri: (null), Code: 0, Content: (null), Error: The SSL connection could not be established, see inner exception.)

执行请求的代码如下:

protected RestResponse Execute(RestRequest request)
{
    var response = client.ExecuteAsync(request).GetAwaiter().GetResult();

    if (response.StatusCode == HttpStatusCode.NotFound)
    {
        return response;
    }
    if (response.StatusCode < HttpStatusCode.OK || response.StatusCode >= HttpStatusCode.BadRequest)
    {
        throw new RestException($"[Rest] Calling {response.ResponseUri} an error occured: {response.StatusCode} - {response.Content}");
    }

    return response;
}

我正在尝试获取内部异常消息,但我不知道如何从 RESTful 响应中捕获该异常。

我尝试过,但没有成功:

if (response.StatusCode < HttpStatusCode.OK || response.StatusCode >= HttpStatusCode.BadRequest)
{
    Console.Write("Inner Exception: " + response.ErrorException.Message);
    throw new RestException($"[Rest] Calling {response.ResponseUri} an error occured: {response.StatusCode} - {response.Content}");
}

我收到相同的消息:“内部异常:无法建立 SSL 连接,请参阅内部异常。

c# .net rest exception testing
1个回答
0
投票

正如用户@PanagiotisKanavos 在评论中指出的那样:

不存在“平静”的反应。你只能得到什么 服务器发送。有一个标准的问题详细信息响应 在RFC 9457中指定。您发布的内容只是

Message
.NET 异常的一部分,而不是任何服务器响应。 (...) 在您发布的代码中,
Console.Write("Inner Exception: " + response.ErrorException.Message);
仅提取消息部分 例外。而是写出整个异常文本。那将 包括所有内部异常和堆栈跟踪。
Console.WriteLine("Inner Exception: {0}",response.ErrorException);
。 更好的是使用正确的日志记录而不是写入控制台。

我按照他说的做了,我找到了我要找的东西。

© www.soinside.com 2019 - 2024. All rights reserved.