DevPath
Foundation lesson · 14 min

Test failure paths as contracts

Make error handling precise and test the behavior around bad input.

Catch what you can handle

A broad except Exception can hide programming mistakes and turn broken state into apparent success. Catch specific expected failures near the boundary, add useful context, and let unexpected errors surface to monitoring.

Test the contract

A useful test checks observable behavior: accepted inputs, rejected inputs and important edge cases. Do not duplicate the function's steps in the assertion. Include an empty collection, a malformed value and a boundary value where relevant.

with pytest.raises(ValueError, match='quantity'):
    parse_quantity('-1')

Translate errors at the edge

A storage layer may raise a database-specific missing-row error. A service can translate that into a domain-level NotFound, and the HTTP layer can turn it into a 404. Preserve the original cause for debugging while returning a safe message to the client. Do not convert a database outage into 'not found'; that would mislead both users and operators.

Write a failure matrix

For each boundary, list valid, missing, malformed, duplicate, and unavailable-dependency cases. Assert the public result and that no forbidden side effect occurred. For example, a rejected duplicate registration must not create a second account. Use fixtures small enough that another developer can understand the expected behavior without reading the implementation.

Check your understanding

Why is `except Exception: return None` risky in a parser?

Show explanation

It masks unexpected bugs and gives callers no clear reason for failure. Catch expected parse errors and report them explicitly.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Validate a request payload with specific errors

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.