private async Task ThrowIfDaprFailure()

in src/Microsoft.Azure.WebJobs.Extensions.Dapr/Services/DaprHttpClient.cs [68:124]


        private async Task ThrowIfDaprFailure(ILogger logger, HttpResponseMessage response)
        {
            if (!response.IsSuccessStatusCode)
            {
                string errorCode = string.Empty;
                string errorMessage = string.Empty;

                if (response.Content != null && response.Content.Headers.ContentLength != 0)
                {
                    JsonElement daprError;

                    try
                    {
                        string content = await response.Content.ReadAsStringAsync();
                        daprError = JsonDocument.Parse(content).RootElement;
                    }
                    catch (Exception e) when (e is JsonException || e is ArgumentException)
                    {
                        logger.LogError($"The returned error message from Dapr Service is not a valid JSON Object. Status Code: {response.StatusCode}");
                        throw new DaprException(
                            response.StatusCode,
                            ErrorCodes.ErrUnknown,
                            "The returned error message from Dapr Service is not a valid JSON Object.",
                            e);
                    }

                    if (daprError.TryGetProperty("message", out JsonElement errorMessageToken))
                    {
                        errorMessage = errorMessageToken.GetRawText();
                    }

                    if (daprError.TryGetProperty("errorCode", out JsonElement errorCodeToken))
                    {
                        errorCode = errorCodeToken.GetRawText();
                    }
                }

                logger.LogError($"Dapr Service returned an error. Status Code: {response.StatusCode}, Error Code: {errorCode}, Error Message: {errorMessage}");

                // avoid potential overrides: specific 404 error messages can be returned from Dapr
                // ex: https://docs.dapr.io/reference/api/actors_api/#get-actor-state
                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new DaprException(
                        response.StatusCode,
                        string.IsNullOrEmpty(errorCode) ? ErrorCodes.ErrDaprResourceDoesNotExist : errorCode,
                        string.IsNullOrEmpty(errorMessage) ? "The requested Dapr resource is not properly configured." : errorMessage);
                }

                throw new DaprException(
                    response.StatusCode,
                    string.IsNullOrEmpty(errorCode) ? ErrorCodes.ErrUnknown : errorCode,
                    string.IsNullOrEmpty(errorMessage) ? "No meaningful error message is returned." : errorMessage);
            }

            return;
        }