Handle InvalidArgumentException thrown by RequestFactory

Hi All,

I have the following problem. If I create a request with invalid headers, my application will die before entering errormiddleware.

Such a request van be:
GET [url]
0: 0

Where “0: 0” is the first header line.

In the $app->run() method, we’ll see that first the request is created and then the request will be handled. So the question is: What is the best way to handle such a user error which happens before entering Error Middleware?

This happens because the HTTP request header name must be an RFC 7230 compatible string.

The name “0” is not a valid request header name.

Instead of calling $app->run() you could pass you own “cleaned” ServerRequest object.


Another approach would be to implement your own ServerRequest factory and “overwrite” the container ServerRequestFactoryInterface definiton.

$app = AppFactory::createFromContainer($container);

Hi odan,

Thank you for taking the time to reply.

I am aware that I could filter out all invalid lines from the request header.

The problem is that we are not in control of what request the user sends. It could be all kinds of invalid.

The user should get bad request error, explaining what went wrong (in my opinion).
Your answer implies to filter out the bad parts and create a request with the remaining good parts.

The problem is also that in Slim Framework, the Error handler only works after the request object is created succesfully.

As a workaround you could try to catch all exceptions from the run() method.


// bootstrap code ...

try {
} catch (Throwable $exception) {
    echo sprintf('Bad Request: %s', $exception->getMessage());

Result: Bad Request: Header name must be an RFC 7230 compatible string.

Hi Odan,

Thanks for your answer. It seems that your solution is the only possible way.

I have a custom error handler with a view template. This means that I must use two different error handlers (my one and also Slim Framework middleware) with the same code.