Search code examples
javamicrosoft-graph-api

How to print Exception in Json format


I am using Graph api java code

 _appClient.users(sFrom)
    .sendMail(UserSendMailParameterSet
        .newBuilder()
        .withMessage(message)
        .withSaveToSentItems(null)
        .build())
    .buildRequest()
    .post();

when I try to hit method I am getting below error..

com.microsoft.graph.http.GraphServiceException: Error code: ErrorAccessDenied Error message: Access to OData is disabled.

POST https://graph.microsoft.com/v1.0/users/{some email ID name}/microsoft.graph.sendMail SdkVersion : graph-java/v5.49.0 [...]

403 : Forbidden [...]

[Some information was truncated for brevity, enable debug logging for more details]

I need it in JSON format , How can I get that, and also I need to get requestid in response..

for example like below

{"error":{"code":"InvalidAuthenticationToken","message":"Access token is empty.","innerError":{"date":"2023-11-09T08:58:24","request-id":"cbe585bc-d83b-4611-9df8-f1e3ad9b74de","client-request-id":"cbe585bc-d83b-4611-9df8-f1e3ad9b74de"}}}

I need RequestID in error response and the exception need to in JOSN format.


Solution

  • You'll need to handle the exceptions and format the responses accordingly. Something along these lines should work

    try {
        _appClient.users(sFrom)
            .sendMail(UserSendMailParameterSet
                .newBuilder()
                .withMessage(message)
                .withSaveToSentItems(null)
                .build())
            .buildRequest()
            .post();
    } catch (GraphServiceException ex) {
        // Handle the GraphServiceException
        String errorResponse = ex.getMessage(); // Get the error response as string
        String requestId = null;
    
        // Try to parse request ID from the error message
        int startIndex = errorResponse.indexOf("request-id");
        if (startIndex != -1) {
            int endIndex = errorResponse.indexOf(",", startIndex);
            if (endIndex != -1) {
                requestId = errorResponse.substring(startIndex, endIndex);
            }
        }
    
        // Process the error response and request ID as needed
        System.out.println("Error Response: " + errorResponse);
        System.out.println("Request ID: " + requestId);
    }