Removing ODerial.Error message deserialization

I have an ASP.NET application that uses the Azure AD Graphics API. Often, when an incorrect operation is performed with the Graph API, an exception is thrown.

The following code shows an invalid call to the Graph API, which will throw an exception:

// Query the Azure AD User
var userToUpdate = await activeDirectoryClient.Users.GetByObjectId("user@domain.net").ExecuteAsync();

// Set given name to an empty string (not allowed)
userToUpdate.GivenName = "";

try
{
    // Update the user in Azure AD
    await userToUpdate.UpdateAsync();
}
catch (Exception e)
{
    // Return exception message
}

The internal exception message is a JSON string with forward slashes in front of each quotation mark. It looks something like this:

"{\"odata.error\":{\"code\":\"Request_BadRequest\",\"message\":{\"lang\":\"en\",\"value\":\"Invalid value specified for property 'givenName' of resource 'User'.\"},\"values\":[{\"item\":\"PropertyName\",\"value\":\"givenName\"},{\"item\":\"PropertyErrorCode\",\"value\":\"InvalidValue\"}]}}"

Attaching a screenshot of the Locals window in which an exception message is detected: Exception Details

I would like to convert this JSON to a .NET object to return detailed error information. I use the JSON.NET library for this, and I assume that JSON is deserialized into an object ODataError:

var error = Newtonsoft.Json.JsonConvert.DeserializeObject<ODataError>(e.InnerException.Message);

null, , .

, JSON? , ?

+4
1

, , - JSON, Microsoft.Azure.ActiveDirectory.GraphClient.ODataError - "odata.error" "" Microsoft.Azure.ActiveDirectory.GraphClient.ODataError

:

internal class ODataError
    {
        [JsonProperty("odata.error")]
        public ODataErrorCodeMessage Error { get; set; }
    }

    internal class ODataErrorCodeMessage
    {
        public string Code { get; set; }

        public ODataErrorMessage Message { get; set; }

        public List<ExtendedErrorValue> Values { get; set; }
    }

    internal class ExtendedErrorValue
    {
        public string Item { get; set; }

        public string Value { get; set; }
    }

    internal class ODataErrorMessage
    {
        public string Lang { get; set; }

        public string Value { get; set; }
    }

JSON :

...
    try
    {
        await ADClient.Users.AddUserAsync(newUser);
        return Result.Ok();
    }
    catch (DataServiceRequestException ex)
    {
        var innerException = ex.InnerException;
        var error = JsonConvert.DeserializeObject<ODataError>(innerException.Message);
        return Result.Fail(new Error(error.Error.Message.Value, error.Error.Code, ex));
    }
+6

Source: https://habr.com/ru/post/1610237/


All Articles