You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

解决RestSharp中SSL连接异常的内部信息获取问题

问题分析

你当前通过response.ErrorException.Message只能拿到外层提示“无法建立SSL连接,请查看内部异常”,是因为真实的错误原因(如证书无效、TLS协议不匹配等)被嵌套在InnerException链中,而非直接在当前异常的Message里。

解决方案

需要递归遍历异常的InnerException属性,拼接所有层级的错误信息,才能拿到完整的错误原因。

1. 编写获取完整异常信息的方法

添加一个工具方法,用于递归提取所有内部异常的消息:

private string GetFullExceptionMessage(Exception ex)
{
    var errorBuilder = new StringBuilder(ex.Message);
    var currentInnerEx = ex.InnerException;
    
    while (currentInnerEx != null)
    {
        errorBuilder.Append($"\n内部异常: {currentInnerEx.Message}");
        currentInnerEx = currentInnerEx.InnerException;
    }
    
    return errorBuilder.ToString();
}

2. 修改错误处理逻辑

在你的请求执行方法中,替换原有的异常输出代码,调用上面的方法获取完整错误信息:

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)
    {
        string fullErrorInfo = response.ErrorException != null ? GetFullExceptionMessage(response.ErrorException) : "未捕获到异常详情";
        Console.WriteLine($"完整错误详情: {fullErrorInfo}");
        
        throw new RestException($"[Rest] 调用 {response.ResponseUri} 出错: {response.StatusCode} - {response.Content}\n详细错误: {fullErrorInfo}");
    }

    return response;
}

额外提示

常见的SSL连接失败深层原因包括:

  • 目标服务器的SSL证书未被本地信任(比如自签名证书)
  • 客户端与服务器的TLS协议版本不兼容(如服务器仅支持TLS1.2,而客户端默认使用更低版本)
  • 本地网络代理拦截了SSL连接

内容的提问来源于stack exchange,提问作者Noob_Number_1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 00:22:26