Errors, empty results and missing records: three application responses

An empty collection, a missing note, invalid input and an unavailable source need different responses. An independent Symfony example with clean HTML pages, separate logging and a complete HTTP test.

Three arched niches in different states form a conceptual metaphor for an empty result, available data and unavailability.

The JSON catalogue has its own /source-notes and /source-notes/{id} routes, SourceNotesController and source_notes/page.html.twig. Preserve /notes and note creation. This exercise reads fixtures/source-notes.json; only tests use var/source-notes-test.json.

There are no notes on the page. This might mean the list is genuinely empty, that a particular note does not exist, or that the application could not read the data at all. All three situations can easily become the same message on screen. They mean different things to the reader, to monitoring and to the next action.

In the article about checking E-01 on demand, the response was evaluated alongside routing, protection and server state. Here I move to the meaning of a response inside the application: what exactly did it manage to establish about the reader’s request?

First decide which question the page answers

A list answers the question “which notes are available?”. An empty result can be the correct answer: the source is accessible, its document has been read and it contains no records. A page for an individual note answers a different question: “is there a record with this identifier?”. Successfully reading the list does not yet mean the required record was found.

The third situation occurs earlier: the source could not be read. The application does not yet know whether it contains records. Returning an empty array here would present a lack of knowledge as knowledge of an absence. This is how a technical failure becomes a convincing but incorrect message.

Before any of these answers, the input itself needs checking. In our example, the reader can limit the list, but not with an arbitrary value. A rejected parameter does not require access to the source. This is a separate step worth making visible in a test, especially when the dependency is unavailable at the same time.

Request and condition Status What the page communicates
The collection was read and contains no records 200 The list is available and empty
The collection was read but the required record is absent 404 No note was found at this address
The list parameter or identifier is invalid 400 The request needs correcting
The teaching file is temporarily unavailable 503 Notes cannot currently be retrieved

Read this table alongside HTTP Semantics: a successful response, an absent representation, a request error and temporary unavailability have different meanings. Our application supplies the specific field rules and messages. Not every server error is temporary unavailability, either.

The practical difference appears in the next action. An empty catalogue can remain open and be populated later. For a missing note, returning to the list or checking the address makes sense. An invalid parameter calls for correcting the request itself. An unavailable source provides no basis for advising someone to recreate a record: the original might still exist even though the application cannot currently see it.

The page text and its status should describe the same outcome. If a friendly failure message is returned as success, an automated client receives contradictory signals. If a truly empty list is marked as an error, an ordinary catalogue state becomes an artificial incident. A numeric status does not replace an explanation, and an explanation does not repair an incorrect status.

Before implementation, ask a simple question: which fact justifies each message? For an empty list, it is a successfully read empty collection. For a missing record, it is a completed search in an accessible collection. With unavailability, no such fact about the data is known. Checking the wording this way can expose an incorrect answer before choosing an exception class or designing the page.

The next step in the shared project

The target is Symfony 8.1, PHP 8.4 or newer and Composer 2. The Symfony release page defines the PHP requirement; it does not establish which version is installed here. We will use the official skeleton, Twig and Filesystem. This exercise needs no database, authentication or working server.

Continue the same Symfony project, article_demo, created from the official skeleton in the earlier articles. Run commands from its root. Add the required dependencies and files while preserving earlier routes, services and data. PHP 8.4+, Symfony 8.1 and Composer 2 remain the example requirements.

php --version
composer --version
composer require 'symfony/twig-bundle:8.1.*' 'symfony/filesystem:8.1.*' --no-interaction
composer require --dev symfony/test-pack --no-interaction
mkdir -p src/Read src/Controller templates/source_notes tests/Controller fixtures var

After installation, save the exact versions and dependency files. Composer lock records a specific package set. The constraint 8.1.* alone does not define that set. Test packages may require additional system PHP extensions.

The source returns data or a specific failure

First write fixtures/source-notes.json:

[
  {"id": 1, "title": "A note about HTTP"},
  {"id": 2, "title": "<em>A literal title</em>"}
]

The identifier belongs to a synthetic note, and row order determines list order. The second title deliberately contains a sequence that resembles markup: the page should display it as text. Extra source fields are not passed to the view.

Create src/Read/NotesUnavailable.php:

<?php

declare(strict_types=1);

namespace App\Read;

final class NotesUnavailable extends \RuntimeException
{
}

Next, src/Read/JsonNotes.php:

<?php

declare(strict_types=1);

namespace App\Read;

use Psr\Log\LoggerInterface;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;

final readonly class JsonNotes
{
    public function __construct(
        private Filesystem $filesystem,
        private LoggerInterface $logger,
        private string $path,
    ) {
    }

    /** @return list<array{id: int, title: string}> */
    public function all(): array
    {
        try {
            $contents = $this->filesystem->readFile($this->path);
        } catch (IOExceptionInterface $failure) {
            $this->logger->error('Notes source could not be read.', ['exception' => $failure]);
            throw new NotesUnavailable('Notes source unavailable.', previous: $failure);
        }

        $rows = json_decode($contents, flags: JSON_THROW_ON_ERROR);

        if (!is_array($rows)) {
            throw new \UnexpectedValueException('The notes fixture must be a JSON array.');
        }

        $notes = [];
        $seen = [];

        foreach ($rows as $row) {
            if (!$row instanceof \stdClass
                || !isset($row->id, $row->title)
                || !is_int($row->id) || $row->id < 1 || $row->id > 999999
                || !is_string($row->title) || $row->title === ''
                || isset($seen[$row->id])) {
                throw new \UnexpectedValueException('The notes fixture contains an invalid row.');
            }

            $seen[$row->id] = true;
            $notes[] = ['id' => $row->id, 'title' => $row->title];
        }

        return $notes;
    }
}

The Filesystem component separates an inability to read a file from its empty contents. The adapter catches only the relevant I/O failure, logs it and raises a specific exception. The controller does not need to know the path or the format of the underlying message.

JSON decoding explicitly uses exception mode. An empty array remains a valid result, while an empty object is an invalid document. We also reject inappropriate fields and duplicate identifiers. This is not a complete validator for arbitrary incoming JSON: the file is a small local fixture with a defined structure.

Corrupt JSON or an invalid structure does not become NotesUnavailable. Those defects follow a different error path. They need diagnosis and correction, not a misleading empty list. Repeating the read indefinitely will not fix an invalid document either.

An empty file also needs to be distinguished from a document containing an empty array. A file with no bytes does not contain the required JSON document. It is not shorthand for “there are no notes”. Similarly, an incorrect identifier type should not silently be repaired through type coercion: the adapter would otherwise conceal a source problem before the controller could classify it correctly.

Logging uses PSR-3 and the standard Symfony logger. The cause stays in the log context; the client does not receive it. Do not add the complete request, passwords or arbitrary reader data there. In this exercise, the read failure itself is logged once per adapter invocation.

The controller translates the outcome into HTTP

Create src/Controller/SourceNotesController.php:

<?php

declare(strict_types=1);

namespace App\Controller;

use App\Read\JsonNotes;
use App\Read\NotesUnavailable;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class SourceNotesController extends AbstractController
{
    public function __construct(private readonly JsonNotes $notes)
    {
    }

    #[Route('/source-notes', name: 'app_source_notes', methods: ['GET'])]
    public function index(Request $request): Response
    {
        $query = $request->query->all();
        $limit = $query['limit'] ?? '10';

        if (!is_string($limit) || preg_match('/\A[1-9][0-9]?\z/', $limit) !== 1
            || (int) $limit > 50) {
            return $this->page('invalid', 'Invalid request', 'Use a limit from 1 to 50.', 400);
        }

        try {
            $notes = $this->notes->all();
        } catch (NotesUnavailable) {
            return $this->unavailable();
        }

        return $this->page('collection', 'Notes', 'No notes yet.', 200, array_slice($notes, 0, (int) $limit));
    }

    #[Route('/source-notes/{id}', name: 'app_source_note', methods: ['GET'])]
    public function show(string $id): Response
    {
        if (preg_match('/\A[1-9][0-9]{0,5}\z/', $id) !== 1) {
            return $this->page('invalid', 'Invalid request', 'Use a positive note identifier.', 400);
        }

        try {
            $notes = $this->notes->all();
        } catch (NotesUnavailable) {
            return $this->unavailable();
        }

        foreach ($notes as $note) {
            if ($note['id'] === (int) $id) {
                return $this->page('item', 'Note', '', 200, [$note]);
            }
        }

        return $this->page('missing', 'Note not found', 'No note exists at this address.', 404);
    }

    private function unavailable(): Response
    {
        return $this->page('unavailable', 'Notes are unavailable', 'Please try again later.', 503);
    }

    /** @param list<array{id: int, title: string}> $notes */
    private function page(string $outcome, string $heading, string $message, int $status, array $notes = []): Response
    {
        return $this->render('source_notes/page.html.twig', [
            'outcome' => $outcome,
            'heading' => $heading,
            'message' => $message,
            'notes' => $notes,
        ], new Response(status: $status, headers: ['Cache-Control' => 'no-store']));
    }
}

The Request and Response objects provide an explicit boundary between parsing input and constructing a response. We read the whole query array so an array-valued parameter also passes through our validation. For limit, we accept a canonical decimal string from 1 to 50, with a default of 10. Unknown query parameters are ignored here; this is not a universal policy for every endpoint.

The identifier must be a positive decimal string without a leading zero, no greater than 999999. Validation happens before reading the source. It does not try to prove that a note exists; that can only be established after reading.

Here, the route deliberately accepts a segment that the controller then validates. Another application might reject that segment during routing. Both approaches need an explicit contract; an address format error should not accidentally be confused with an established absence of a record. This matrix also excludes arbitrary paths that our controller does not serve at all.

The list method can return an empty result. The individual-record method inspects an already-read collection before constructing an absence response. Both catch the specific availability failure. There is no general catch of every exception that returns a successful page.

In this example, status 503 means controlled loss of access to the teaching file, which we will later restore. In a real system, classification depends on the cause: a programming error, persistently incorrect configuration and a failed network intermediary may require other responses. Classifying every exception solely as “something went wrong” is insufficient.

The list limit shortens only the representation. The adapter still reads the entire small document, so this implementation does not demonstrate efficient pagination over a large store. It also does not retain an old copy during a failure. If the application returned stale data, the reader would need a separate agreement about its freshness; silently presenting it as freshly read would be misleading.

The message and the technical details have different readers

Merge this fragment into the existing services block in config/services.yaml, preserving earlier registrations and imports. Keep the rest of the file.

services:
    App\Read\JsonNotes:
        arguments:
            $path: '%kernel.project_dir%/fixtures/source-notes.json'
    App\Controller\SourceNotesController: ~

Merge this definition into the existing services block in config/services_test.yaml, preserving earlier test settings:

services:
    App\Read\JsonNotes:
        autowire: true
        arguments:
            $path: '%kernel.project_dir%/var/source-notes-test.json'

The path depends on the environment: browser practice uses its own file and the test uses another. The filename does not come from the user’s request. The exception is not registered as a service. The installed FrameworkBundle provides the standard logger; this small exercise does not require a separate Monolog installation.

Create templates/source_notes/page.html.twig:

{% autoescape 'html' %}
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{ heading }}</title>
</head>
<body>
<main data-outcome="{{ outcome }}">
    <h1>{{ heading }}</h1>
    {% if notes %}
        <ul>
        {% for note in notes %}
            <li><a href="{{ path('app_source_note', {id: note.id}) }}">{{ note.title }}</a></li>
        {% endfor %}
        </ul>
    {% else %}
        <p>{{ message }}</p>
    {% endif %}
    <p><a href="{{ path('app_source_notes') }}">All notes</a></p>
</main>
</body>
</html>
{% endautoescape %}

Twig HTML escaping applies to variables in the template. The page receives a concise outcome and fixed messages; it does not receive an exception object. Escaping an error message does not make exposing an internal path, SQL or configuration appropriate.

Every response from this controller sets Cache-Control: no-store. This deliberately simplifies the local experiment so a previous page does not interfere with observing a new state. As the HTTP Caching standard explains, this directive is not a sufficient privacy mechanism. A real catalogue’s caching policy needs a separate decision.

The Retry-After header is omitted because we have no confirmed recovery time. “Please try again later” should not invent a precise countdown. The reader also does not need instructions to modify their note when the dependency’s operator must resolve the problem.

The operator needs the cause of the failure, while the visitor needs an understandable state and a safe next action. Separate channels meet these needs without copying the exception message into the template. Even a seemingly harmless path exposes environment details and quickly becomes an unstable part of the interface. A fixed message can be translated or changed without restructuring the technical log.

Check responses through the actual HTTP path

Write the complete tests/Controller/SourceNotesControllerTest.php:

<?php

declare(strict_types=1);

namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\KernelBrowser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Filesystem\Filesystem;

final class SourceNotesControllerTest extends WebTestCase
{
    private KernelBrowser $client;
    private ?string $path = null;

    protected function setUp(): void
    {
        parent::setUp();
        self::ensureKernelShutdown();
        $this->client = static::createClient();
        $path = self::getContainer()->getParameter('kernel.project_dir').'/var/source-notes-test.json';

        if (file_exists($path)) {
            throw new \LogicException('Use a fresh lab without an existing source-notes-test.json.');
        }

        $this->path = $path;
        (new Filesystem())->dumpFile($path, '[{"id":1,"title":"First"},{"id":2,"title":"<em>Literal</em>"}]');
    }

    protected function tearDown(): void
    {
        if ($this->path !== null && is_file($this->path)) {
            unlink($this->path);
        }
        parent::tearDown();
    }

    public function testACollectionCanBeLimited(): void
    {
        $this->client->request('GET', '/source-notes?limit=1');
        self::assertResponseStatusCodeSame(200);
        self::assertSelectorCount(1, 'main li');
        self::assertSelectorTextContains('main li', 'First');
    }

    public function testAnEmptyCollectionIsASuccess(): void
    {
        file_put_contents($this->path, '[]');
        $this->client->request('GET', '/source-notes');
        self::assertResponseStatusCodeSame(200);
        self::assertSelectorExists('[data-outcome="collection"]');
        self::assertSelectorTextContains('main', 'No notes yet.');
    }

    public function testAnExistingItemPreservesLiteralText(): void
    {
        $this->client->request('GET', '/source-notes/2');
        self::assertResponseStatusCodeSame(200);
        self::assertSelectorTextContains('main li', '<em>Literal</em>');
        self::assertSelectorNotExists('main em');
    }

    public function testAMissingItemHasItsOwnResponse(): void
    {
        $this->client->request('GET', '/source-notes/3');
        self::assertResponseStatusCodeSame(404);
        self::assertSelectorExists('[data-outcome="missing"]');
        self::assertSelectorTextContains('main', 'No note exists at this address.');
        self::assertSelectorNotExists('main li');
    }

    public function testInvalidInputHasACleanResponse(): void
    {
        foreach (['/source-notes?limit=0', '/source-notes?limit=51', '/source-notes?limit=x', '/source-notes?limit[]=1', '/source-notes/01'] as $uri) {
            $this->client->request('GET', $uri);
            self::assertResponseStatusCodeSame(400);
            self::assertSelectorExists('[data-outcome="invalid"]');
            self::assertSelectorNotExists('main li');
        }
    }

    public function testInvalidInputDoesNotNeedTheSource(): void
    {
        unlink($this->path);
        $this->client->request('GET', '/source-notes?limit=x');
        self::assertResponseStatusCodeSame(400);
        self::assertSelectorExists('[data-outcome="invalid"]');
    }

    public function testUnavailableSourceIsNotEmptyOrMissing(): void
    {
        unlink($this->path);

        foreach (['/source-notes', '/source-notes/1'] as $uri) {
            $this->client->request('GET', $uri);
            self::assertResponseStatusCodeSame(503);
            self::assertSelectorExists('[data-outcome="unavailable"]');
            self::assertSelectorNotExists('main li');
            $response = $this->client->getResponse();
            self::assertTrue($response->headers->hasCacheControlDirective('no-store'));
            self::assertFalse($response->headers->has('Retry-After'));
            self::assertStringNotContainsString($this->path, $response->getContent());
            self::assertStringNotContainsString('NotesUnavailable', $response->getContent());
        }
    }
}

Correct numeric statuses are not enough. The checks cover the contents of an empty list, the distinct absence of a record, title escaping, rejection of an array instead of a string, and the absence of an internal path in the response. Source failure is checked for both routes. A separate scenario is intended to establish that invalid input is rejected before accessing the unavailable file.

After saving all the files shown above:

composer validate --strict --no-check-publish
composer check-platform-reqs
composer show --locked --format=json
sha256sum composer.lock symfony.lock
find src tests -name '*.php' -print0 | xargs -0 -n1 php -l
php bin/console lint:yaml config/services.yaml
php bin/console lint:twig templates/source_notes
php bin/console lint:container --env=dev
php bin/console lint:container --env=test
APP_ENV=test php bin/phpunit tests/Controller/SourceNotesControllerTest.php --testdox

Run the test file actually included here. Successful syntax parsing does not replace its execution, and a check of the happy path alone does not establish the rest of the matrix. If a test fails, first determine which behaviour it observed, then change the implementation or a justified contract.

See the difference in a browser and curl

APP_ENV=dev APP_DEBUG=0 php -S 127.0.0.1:8000 -t public public/index.php

Disabling debug does not replace handling expected failures. It also prevents an unexpected error from showing the reader a developer’s diagnostic page. The built-in PHP server is intended for local practice, not public deployment.

In another terminal, check a known record, a missing record and an invalid parameter:

curl --silent --show-error --max-time 5 --dump-header - 'http://127.0.0.1:8000/source-notes/1'
curl --silent --show-error --max-time 5 --dump-header - 'http://127.0.0.1:8000/source-notes/99'
curl --silent --show-error --max-time 5 --dump-header - 'http://127.0.0.1:8000/source-notes?limit=x'

In a second terminal, change only the teaching fixture. mktemp creates a unique backup; check copying succeeds and install the restoration trap before changing data. A failed restoration leaves the backup intact. Keep the experiment away from working data.

(
    ARTICLE_SOURCE_BACKUP="$(mktemp "${TMPDIR:-/tmp}/article-source-notes.XXXXXX")" || exit 1
    if ! cp fixtures/source-notes.json "$ARTICLE_SOURCE_BACKUP"; then
        rm -f "$ARTICLE_SOURCE_BACKUP"
        exit 1
    fi
    trap 'cp "$ARTICLE_SOURCE_BACKUP" fixtures/source-notes.json && rm -f "$ARTICLE_SOURCE_BACKUP"' EXIT
    printf '[]\n' > fixtures/source-notes.json
    curl --silent --show-error --max-time 5 --dump-header - 'http://127.0.0.1:8000/source-notes'
    rm fixtures/source-notes.json
    curl --silent --show-error --max-time 5 --dump-header - 'http://127.0.0.1:8000/source-notes'
)

The first request is expected to show a successful empty list and the second to show unavailability. After the fixture is restored, the page should show records again. There is no request parameter that artificially enables failure: the local dependency itself changes.

Pay attention to both status and body. An ordinary successful curl exit means the transfer finished, not necessarily that the HTTP outcome was successful; the curl manual explains this separately. This distinction matters in manual checks and automated monitors alike. When a source is unavailable, the correct response preserves honest uncertainty and gives the operator a way to find the cause.

  1. Symfony Core The first useful page after the Symfony skeleton: a catalogue of learning notes
  2. Symfony Core Form validation and product rules: why they are different checks
  3. API API errors a client can handle