Handle a failed sales system API response (exception)

Now that the successful work items have been handled, it's time to do something about the failing requests.

In case of an application exception, you release the work item as failed and add information about the failure:

@task def consume_traffic_data(): """ Inhuman Insurance, Inc. Artificial Intelligence System robot. Consumes traffic data work items. """ process_traffic_data() def process_traffic_data(): for item in workitems.inputs: traffic_data = item.payload["traffic_data"] if len(traffic_data["country"]) == 3: status, return_json = post_traffic_data_to_sales_system(traffic_data) if status == 200: item.done() else: item.fail( exception_type="APPLICATION", code="TRAFFIC_DATA_POST_FAILED", message=return_json["message"], ) def post_traffic_data_to_sales_system(traffic_data): url = "https://robocorp.com/inhuman-insurance-inc/sales-system-api" response = requests.post(url, json=traffic_data) return response.status_code, response.json()
  • You added an extra return value to post_traffic_data_to_sales_system(). When you are interested in more than just one information, python allows multiple returns to make your life easier. In our case, we need both the status and the response json to see what happened after our call.
  • You added an else statement to handle the application failure case, when the status is different from 200.
  • When item.fail() is called, an exception is logged and the work item is released as FAILED. More information is added by providing the exception type (APPLICATION - indicating a technical exception), a custom code (for exception filtering purposes in Control Room), and a message (to be displayed in Control Room).

You run the consumer task. This time, the robot does not give up when an exception occurs. It logs the error, releases the work item as failed, and continues with the rest of the work items.

Releasing item '28' with FAILED state and exception: {'type': 'APPLICATION', 'code': 'TRAFFIC_DATA_POST_FAILED', 'message': 'Internal error.'}

Excellent! Now the robot knows how to handle both successful and failed API requests.