Graph SDK V5如何访问ODataError的Error.InnerError.Code?
解决新版Graph SDK中ODataError无法访问InnerError.Code的问题
方法一:通过字典类型访问InnerError属性
新版Graph SDK的ODataError类中,InnerError本质是键值对结构(通常为IDictionary<string, object>),可以直接通过键名提取code:
try { // 调用Graph API的业务代码 } catch (ODataError odataError) { if (odataError.InnerError is IDictionary<string, object> innerErrorDict) { if (innerErrorDict.TryGetValue("code", out var innerCodeObj)) { string innerErrorCode = innerCodeObj.ToString(); // 处理ChannelNameAlreadyExist这类业务错误码 } } }
方法二:自定义类反序列化(你提到的方案)
如果需要强类型支持,可以创建匹配响应结构的自定义类,直接反序列化原始错误响应:
// 自定义错误结构类 public class CustomODataError { [JsonPropertyName("error")] public CustomErrorDetail Error { get; set; } } public class CustomErrorDetail { public string Code { get; set; } public string Message { get; set; } public CustomInnerError InnerError { get; set; } } public class CustomInnerError { public string Message { get; set; } public string Code { get; set; } public DateTime Date { get; set; } [JsonPropertyName("request-id")] public string RequestId { get; set; } [JsonPropertyName("client-request-id")] public string ClientRequestId { get; set; } } // 使用示例 catch (ODataError odataError) { // 获取原始错误响应JSON字符串(可通过异常的Response属性提取) string rawErrorJson = GetRawErrorResponse(odataError); CustomODataError customError = JsonSerializer.Deserialize<CustomODataError>(rawErrorJson); string innerErrorCode = customError.Error.InnerError.Code; }
方法三:使用动态类型快速访问
如果不需要严格类型校验,可通过dynamic简化操作:
catch (ODataError odataError) { dynamic innerError = odataError.InnerError; string innerErrorCode = innerError.code; }
注意:动态类型存在运行时类型错误风险,仅适合快速验证场景。
内容的提问来源于stack exchange,提问作者Dethras
相关产品推荐
相关产品推荐

