Throwing a exception with HTTP Status code in Flow Framework

When I started getting familiar with exceptions in my every day coding (it took me some time, honest!) I’ve found that me throwing a exception can some time be directly “connected” to what respons I’m giving to the request.

Say, a resource is requested with a identifier, but it doesn’t exists. That will equal a HTTP 404 - Not found.

And with exceptions in the Flow Framework you can do jus that. And even though you might not have given it any thougts, it’s already used. In the NoSuchControllerException used for when routing and controller doesn’t match, the $statusCode property is set to 404

class NoSuchControllerException extends \Neos\Flow\Mvc\Exception
{
    /**
     * @var integer
     */
    protected $statusCode = 404;
}

This bubles up to the exception handler and passes on the $statusCode to the HTTP Response.

And you can do the same

Today I worked on security related checks on a request. If the given parameter doesn’t fit the authenticated user (trying to access something you should not) I’d like to return a HTTP 403 - Forbidden

So I did, by throwing a exception like this:

<?php

namespace Dafis\DataApi\Exception;

use Neos\Flow\Exception;

final class InvalidOrganizationGivenException extends Exception
{
    protected $statusCode = 403;
    protected $referenceCode = 1608288610;
}

Important notice: You need to extend the \Neos\Flow\Exception class for this to have effect

And now having that bubling up, to the response (in my case a API endpoint) which returns the status code to my frontend, and that can be nicely handled.

Biggest benefit, is that I need no additional conditions around my code, for returning a error message 🤩

Leave a Reply

Your email address will not be published. Required fields are marked *