diff --git a/common/src/service/ExceptionHandlingHelper.cs b/common/src/service/ExceptionHandlingHelper.cs index a023c4140a..6775286777 100644 --- a/common/src/service/ExceptionHandlingHelper.cs +++ b/common/src/service/ExceptionHandlingHelper.cs @@ -102,8 +102,13 @@ public static Task GetExceptionMessageAsync(HttpResponseMessage response /// The fully-qualified error code, or the response status code, if no error code was provided. public static async Task GetExceptionCodeAsync(HttpResponseMessage response) { + string responseContentStr = ""; + if (response.Content == null) + { + return ErrorCode.InvalidErrorCode; + } // First we will attempt to retrieve the error code from the response content. - string responseContentStr = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + responseContentStr = await response.Content.ReadAsStringAsync().ConfigureAwait(false); // There are two things to consider when surfacing service errors to the user, the 6-digit error code and the code description. Ideally, when a backend service // returns an error, both of these fields are set in the same place. However, IoT hub is returning the 6-digit code in the response content, while @@ -120,7 +125,11 @@ public static async Task GetExceptionCodeAsync(HttpResponseMessage re try { - Dictionary messageFields = JsonConvert.DeserializeObject>(responseContent.Message); + var messageFields = new Dictionary(); + if (responseContent?.Message != null) + { + messageFields = JsonConvert.DeserializeObject>(responseContent.Message); + } if (messageFields != null && messageFields.TryGetValue(CommonConstants.ErrorCode, out string errorCodeObj)) @@ -157,7 +166,8 @@ public static async Task GetExceptionCodeAsync(HttpResponseMessage re #endif { string[] errorCodeFields = messageField.Split(errorCodeDelimiter); - if (Enum.TryParse(errorCodeFields[1], out ErrorCode errorCode)) + if (errorCodeFields.Length > 1 + && Enum.TryParse(errorCodeFields[1], out ErrorCode errorCode)) { errorCodeValue = (int)errorCode; } @@ -184,8 +194,14 @@ public static async Task GetExceptionCodeAsync(HttpResponseMessage re return ErrorCode.InvalidErrorCode; } - // Now that we retrieved the integer error code from the response content, we will retrieve the error description from the header. - string headerErrorCodeString = response.Headers.GetFirstValueOrNull(CommonConstants.HttpErrorCodeName); + string headerErrorCodeString = null; + + if (response.Headers != null) + { + // Now that we retrieved the integer error code from the response content, we will retrieve the error description from the header. + headerErrorCodeString = response.Headers.GetFirstValueOrNull(CommonConstants.HttpErrorCodeName); + } + if (headerErrorCodeString != null && Enum.TryParse(headerErrorCodeString, out ErrorCode headerErrorCode)) {