3
\$\begingroup\$

I'm trying to add error handling and response logging for API calls. The way I have my application (chatbot) set up is that a helper function is called from the main dialog, and that helper function calls the API. I believe this is standard practice. What I'm not sure on is how I should be catching errors in the process and where the appropriate point to do various logging is. I've considered the approach of putting all error catching in the helper, but if the API call fails, I still need an exception path in my main dialog. So what I've settled on is a try/catch block to call the function, which will catch API call failure in the helper. If the API call is successful, I'm logging the result from the helper. If the API call fails, I'm logging the failure from the main dialog. Here are the appropriate code snippets:

statusDialog.js

try {
    const orderResponse = await orderStatusHelper.getStatus(orderNumber);
} catch(err) {
    appInsightsClient.trackTrace({
        message: `API Response - ${path.basename(__filename)}`,
        severity: 3,
        properties: {'error':err.message,'callStack':err.stack}
    });
}

orderStatusHelper.js

let response = await request ({
    url:url,
    method: 'POST',
    headers: headers,
    json: postData
});

// If call fails, main function goes to catch block
// If call succeeds, log response and return result
appInsightsClient.trackTrace({
    message: `API Response - ${path.basename(__filename)}`,
    severity: 1,
    properties: {response}
});
return response;

I would appreciate feedback on

  • If this is the proper method to catch errors when I'm calling a function that's calling an API
  • If I am logging the response (or lack thereof) in the right spot
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.