Authors
Prerequisites
In this tutorial, you will learn how to catch errors within the API assembly. Errors can range from built-in (ie connection failure) or custom (ie InsuffienctFundsException). The API assembly provides a single global error handle to catch errors thrown by any policy.
Instructions:
- Note: If you did not complete previous tutorial, import the API definitions file from https://raw.githubusercontent.com/ozairs/apiconnect/master/error-handling/weather-provider-api_1.0.0.yaml. See instructions here
- Open the API designer and select the Assembly tab.
- The Show Catches toggle provides an visible area to define error handling logic for common error conditions. The default errors are defined here. Multiple approaches are available to throw errors:
- The API assembly provides a
throwpolicy that triggers the global error handler into the catch space, which can contain policies to return an error message to the client. - Throw errors in your JavaScript code when an error condition is reached. For example, when the Invoke policy returns an non-200 error, you can check the response variable using GatewayScript and throw errors programmatically. You will use this approach to throw and catch errors.
- The API assembly provides a
- Switch back to the existing JavaScript policy. Replace the existing code with the following:
//get the payload var json = apim.getvariable('message'); console.info("json %s", JSON.stringify(json)); //check error in response if (json.body && json.status.code == '404') { console.error("throwing apim error %s", JSON.stringify(json.status.code)); apim.error('ConnectionError', 500, 'Service Error', 'Failed to retrieve data'); } else { json.body.platform = 'Powered by IBM API Connect'; json.headers.platform = 'Powered by IBM API Connect'; } //set the payload apim.setvariable('message.body', json.body); apim.setvariable('message.headers', json.headers); - Click the catch area and the catch+ button and add the following errors:
- Close the panel once done.
- Each error condition can execute a set of policies. Add a set-variable action and click the +Create button. Name it
Rewrite Errorand enter the following: - Save the assembly.
- Testing this policy requires an actual error to occur. Click the Play icon to open the built-in test tool. Test the get /current operation, enter an zipcode value of
0. You should see the error message{"message": "Error occurred during search operation."}.
In this tutorial, you learned how to catch errors during execution of the API assembly and return an error message back to the API consumer.
Next Tutorial: Protect access to API services with Auth0 & JWT