In our connected, online world, errors are bound to happen. Providing helpful information to our end-users when errors happen is an important task for all developers. In the .Net world, this means catching exceptions and logging/reporting them for followup or resolution.
In the Microsoft Graph SDK for .Net, there are two exception-derived types: ClientException and ServiceException. Both of these wrap the Error object (also documented as the Error resource type if you prefer non-C# information), which contains a code and message to describe the error.
- A ClientException is typically thrown when data or parameters that you provide to the library are not valid. (In the 1.17 release, this is primarily when submitting a batch of requests.)
- A ServiceException is thrown for any non-success status code returned by the service.
When a ServiceException is thrown, the HttpResponse often contains information about the error. In the case of the DirectoryObject.ValidateProperties operation, that response is crucial! If you need to access this information, you will need to catch the ServiceException and drill into Error object.
try
{
await graphServiceClient
.DirectoryObjects
.ValidateProperties("Group", "dark mode", "darkmode", new Guid("977c23bf-..."))
.Request()
.PostAsync();
}
catch (Microsoft.Graph.ServiceException svcEx)
{
var additionalData = svcEx.Error.AdditionalData;
var details = additionalData["details"];
}
The Error object is hydrated from the response JSON just like every other response in the SDK. If the response has a JToken that does not match a property, it is added to the AdditionalData dictionary. You will need to know the JToken (key) name, which should be available from the documentation. (Or, you could use the LoggingMessageHandler to capture the raw response and review that instead.)