AlgoViz

API error handling

easy 24 min

Good error handling tells the caller what went wrong, why, and what to do next, in one format for the whole API.

See it run

Follow failures from the place they happen to the answer, and from the answer to the client's next step.

Operations

Status explorer

Ten status codes with one example each. 4xx: the request must change. 5xx: we failed.

Step 1 of 10

400 Bad Request

statusnameexample
400Bad Requestmissing field email
401Unauthorizedexpired token
403Forbiddencannot delete admins
404Not Foundproduct id unknown
409Conflictemail registered
422Unprocessableprice not positive
429Too Many Requestsretry after 60 s
500Server Errorunexpected error
502Bad Gatewaypayment answered badly
503Unavailableunder maintenance

Caller: correct the request

The request is broken: a required field is missing.

Step 1: 400 Bad Request

STATUS = {    "unreadable": 400, "who_are_you": 401, "not_allowed": 403,    "unknown_id": 404, "conflict": 409, "bad_values": 422,    "too_many": 429, "bug": 500, "bad_upstream": 502, "down": 503,}
Caller does
Reads status
Team does
Picks one rule

If you hesitate between two codes, ask what the caller should do next. That decides it.

In the real world

The same api error handling doing real jobs. Pick one and step through it.

The same wrong input, a bad and a good answer.

Step 1 of 2

Bad API

Our systemClient appsomething wrongAPI gatewayOrder serviceemail invalidDatabaseLog store

Nothing to act on

500 and something went wrong. The person tries the same thing again.

Step 1: Bad API

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • 200 OK with an error inside

    critical

    Caches store it, monitors count it as success and clients forget to look.

    Wrong
    return 200, {"success": False, "msg": "no"}
    Right
    return 409, problem("DUPLICATE_ENTRY", ...)
  • Showing the exception

    critical

    Host names, queries and file paths help an attacker and nobody else.

    Wrong
    except Exception as e:    return 500, {"error": str(e)}
    Right
    except Exception as e:    log(trace, e, stack=True)    return 500, problem(UNEXPECTED, trace)
  • Retrying everything

    major

    A 422 never gets better, and a repeated POST may charge twice.

    Wrong
    while not ok:    call()
    Right
    if status in RETRYABLE and repeatable and n < 4:    sleep(backoff(n))
  • Stopping at the first field

    minor

    Three mistakes become three slow trips for the user.

    Wrong
    if bad(quantity): raise Error("quantity")if bad(zip): raise Error("zip")
    Right
    errors = [e for e in checks(order) if e]if errors: raise ValidationError(errors)

Interview tips

  • How to explain it

    • Status for the class, code for programs, sentence for people.
    • One handler, one shape, unknown becomes 500.
    • Details in the logs, linked by a trace id.
  • Memory trick: ERROR

    • Explicit codes, Readable messages.
    • Recovery hints, Observability.
    • Retry guidance.
  • Say yes to a retry when

    • 429 after its wait.
    • 502, 503, 504, with care 500.
    • The call is repeatable and attempts are few.
  • Never

    • Reveal internals.
    • Say which half of a login was wrong.
    • Treat no answer as failure.