Error and Exception Handling · 20 / 20 Exercise Hard

Retries with a custom error

Objective

A custom error can carry data (attributes) besides the message, so whoever catches it can decide what to do. Here we simulate calls to a service that sometimes fails.

Instructions

  • The first line has the number n of cases; each one is a line with the status codes the service would return on each attempt (for example 503 500 200).
  • Make up to 3 attempts. Show Attempt k: code for each attempt. A code below 500 ends the calls: from 200 to 299 show Success; otherwise Rejected: code. If the 3 attempts give 5xx, raise ApiError with the attributes status and attempts, and show Final failure: code after 3 attempts.
Input
3
503 500 200
404
500 502 503
Output
Attempt 1: 503
Attempt 2: 500
Attempt 3: 200
Success
Attempt 1: 404
Rejected: 404
Attempt 1: 500
Attempt 2: 502
Attempt 3: 503
Final failure: 503 after 3 attempts

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise