How do you design error handling in firmware?
Short answer: Combine several layers: functions return explicit status codes that callers must check; assert-style checks catch programming errors during development; peripherals and communication have timeouts and retries; hardware faults (HardFault, bus errors) are caught by fault handlers that record diagnostic data; and the system has a defined recovery strategy (retry, degrade, safe state, reset) plus a watchdog as the last line of defence. Errors are logged so field failures can be analysed.
1. Status codes
typedef enum {
ERR_OK = 0, ERR_TIMEOUT, ERR_BUSY, ERR_CRC, ERR_PARAM, ERR_NO_MEM, ERR_HW
} err_t;
err_t sensor_read(int16_t *out) __attribute__((warn_unused_result));
err_t e = sensor_read(&t);
if (e != ERR_OK) { log_error(MOD_SENSOR, e); return e; } /* propagate */
2. Classify errors and choose a response
| Class | Example | Response |
|---|---|---|
| Transient | I2C NACK, CRC error on a message | retry with a limit and back-off |
| Recoverable hardware | sensor not responding | re-initialise the peripheral, bus recovery, mark data invalid |
| Persistent | sensor dead, flash wear-out | degrade: use a default, disable the feature, report it |
| Programming error | NULL argument, impossible state | assert → fault handler → safe state/reset (do not continue with corrupted logic) |
| Fatal | stack overflow, HardFault | record context in .noinit, enter safe state, reset |
3. Fault handlers: implement HardFault_Handler (and MemManage/Bus/Usage faults) to save the stacked PC, LR, fault status registers (CFSR, HFSR, MMFAR, BFAR) into a .noinit area, put outputs into a safe state (motors off, valves closed), then reset. After reboot, read and report the record.
4. Timeouts everywhere: no while (!(SR & FLAG)); without an escape; a missing hardware response should not hang the system.
5. Safe state: define what "safe" means for the product (e.g. heater off, actuators de-energised), and make sure every fatal path goes there quickly.
6. Watchdog for errors you did not anticipate, plus a reset counter to detect boot loops and switch to a recovery/safe mode.
7. Logging and telemetry: a small ring buffer of error codes with timestamps, kept in RAM (.noinit) or flash, readable over a debug interface or sent to the cloud.
8. Defensive input handling: validate all external input (message lengths, ranges, enum values); never trust data from the outside.
What interviewers want to hear: errors are expected and handled by design, not ignored; programming errors fail fast and loud in development; production devices recover on their own and leave evidence behind.