Error Handling and Defensive Programming Questions
Covers designing and implementing defensive, fault tolerant code and system behaviors to prevent and mitigate production failures. Topics include input validation and sanitization, null and missing data handling, overflow and boundary protections, exception handling and propagation patterns, clear error reporting and structured logging for observability, graceful degradation and fallback strategies, retry and backoff policies and idempotency for safe retries. Also address concurrency and synchronization concerns, resource and memory management to avoid exhaustion, security related input checks, and how to document and escalate residual risks. Candidates should discuss pragmatic trade offs between robustness and complexity, show concrete defensive checks and assertions, and describe test strategies for error paths including unit tests and integration tests and how monitoring and operational responses tie into robustness.
Sample Answer
-- Pseudocode Lua: if not exists(key) then HMSET key owner, status=in-progress; EXPIRE key lease_ttl; return "acquired" else return hgetall(key) endSample Answer
/**
* Safely parse and sanitize JSON from untrusted source.
* - maxBytes: size limit for raw input
* - whitelist: Set or array of allowed top-level fields
* Returns: { ok: true, data: sanitizedObject } or { ok: false, error: { code, summary, details } }
*/
function safeParseJson(raw, { maxBytes = 10_000, whitelist = [] } = {}) {
// size check (UTF-8 bytes)
const size = typeof raw === 'string' ? new TextEncoder().encode(raw).length : 0;
if (size === 0 || size > maxBytes) {
return { ok: false, error: { code: 'SIZE_LIMIT', summary: 'Payload size invalid', details: { size, maxBytes } } };
}
let parsed;
try {
parsed = JSON.parse(raw);
} catch (e) {
return { ok: false, error: { code: 'INVALID_JSON', summary: 'Malformed JSON', details: e.message } };
}
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
return { ok: false, error: { code: 'INVALID_TYPE', summary: 'Top-level must be an object', details: typeof parsed } };
}
const allowed = new Set(whitelist);
const sanitized = {};
for (const key of Object.keys(parsed)) {
if (allowed.size && !allowed.has(key)) continue; // drop disallowed fields
const val = parsed[key];
// defend: only accept primitives and plain objects (shallow)
if (
val === null ||
typeof val === 'string' ||
typeof val === 'number' ||
typeof val === 'boolean'
) {
sanitized[key] = val;
} else if (typeof val === 'object' && val !== null && !Array.isArray(val)) {
// shallow copy of plain object but strip functions/prototypes
sanitized[key] = Object.fromEntries(
Object.entries(val).filter(([k, v]) => ['string', 'number', 'boolean', 'object'].includes(typeof v))
);
} // else ignore arrays, functions, etc.
}
return { ok: true, data: sanitized };
}Sample Answer
-- args: KEYS[1], ARGV[1]=owner, ARGV[2]=in_progress_ttl (ms)
local v = redis.call("GET", KEYS[1])
if not v then
local val = ARGV[1] .. "|IN_PROGRESS"
redis.call("SET", KEYS[1], val, "PX", ARGV[2], "NX")
return {ok="ACQUIRED"}
else
-- caller parses v to decide
return {ok=v}
endSample Answer
import functools
import threading
from typing import Callable, TypeVar
F = TypeVar("F", bound=Callable[..., object])
def retry_once_on_exception(func: F) -> F:
"""Retry the wrapped function one time on exception, then raise the last exception."""
lock = threading.RLock() # optional per-wrapped-function lock
@functools.wraps(func)
def wrapper(*args, **kwargs):
# First attempt
try:
return func(*args, **kwargs)
except Exception as first_exc:
# Retry once inside lock to make retry behavior atomic per-call if needed
with lock:
try:
return func(*args, **kwargs)
except Exception:
# Re-raise the last exception (preserve traceback implicitly)
raise
return wrapper # type: ignore@retry_once_on_exception
def fetch_remote_resource():
# idempotent fetch (safe to call twice)
...Sample Answer
Unlock Full Question Bank
Get access to hundreds of Error Handling and Defensive Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.