PHP / CHAPTER 10

Parsing and exception contracts

Intermediate

Turn malformed input into an explicit, diagnosable outcome.

By the end of this chapter

  • Separate JSON syntax from application schema
  • Use throwing JSON decoding when appropriate
  • Catch only failures a layer can handle

The idea

Parsing answers whether text follows a syntax; validation answers whether its value satisfies your application’s rules. JSON can validly contain null, a scalar, or an object with missing fields. Decoding successfully therefore does not establish that a requested field exists or has the right type. Validate the resulting shape before using it, and distinguish an absent field from a field explicitly containing null.

JSON_THROW_ON_ERROR makes malformed JSON raise JsonException instead of relying on a separate error inspection path. Catch that exception where the application can report or recover from invalid input. Avoid swallowing every Throwable around unrelated business logic. A finally block can perform required cleanup regardless of success, but it should not return a replacement value that hides the original result or failure.

PHP example
<?php
try {
    $data = json_decode("{bad}", true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $error) {
    echo "Invalid JSON
";
}
Result
Invalid JSON

The malformed text triggers JsonException because the flag requests throwing behavior. Schema validation would still be needed for syntactically valid input.

Try it yourself

Decode a JSON object with a nonempty string id and return a clear invalid-input result for syntax or schema failures.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which function distinguishes a present null value from an absent array key?