← Lesson
Coerce and Structured Errors
Joeven
Run
Reset
Python loads on first run
import json JOBS = {17: {"status": "failed"}} def coerce_job_id(raw): if isinstance(raw, bool): return None if isinstance(raw, int): n = raw elif isinstance(raw, str) and raw.isdigit(): n = int(raw) else: return None if n < 1: return None return n def get_job(raw_id): job_id = coerce_job_id(raw_id) if job_id is None: return { "error": "invalid_args", "field": "job_id", "hint": "job_id must be a positive integer", "got": raw_id, } row = JOBS.get(job_id) if row is None: return {"error": "not_found", "job_id": job_id, "hint": "ids look like 17, 42"} out = {"ok": True, "job_id": job_id} out.update(row) return out for sample in ["17", 17, -1, "abc", 99, True]: print(json.dumps({"in": sample, "out": get_job(sample)}))
Run to execute this in your browser. Nothing is sent to a server.