cyclone200 cyclone200 - 2 months ago 12
PHP Question

Silex Routing with wildcard throws error 500

I've just noticed that when there is a wrong URL like : http://example.com/articles/qslkdqm ; the controller throws an error 500 instead of an error 404.

So, I tried to manually change the StatusCode when the controller checks the slug to retrieve the data :

Controller

$article = $app['dao.article']->getArticle($slug);
if (!$article) {
$response = new Response();
$response->setStatusCode(404);
}


But it doesn't work and still throws an error 500.

Is that normal? We fully agree that this should be a 404?

I understand that it throws an error 500 because some variables are not defined (ie. the title of the article). Does that mean that in each variable call, I just check for its existence like:

{% if title is defined %}
...
{% endif %}


?

Thank you for your answer.

Answer

you can stop application with 404 error this way:

if (!$article) {
    $app->abort(404);
}

or

if (!$article) {
    throw new \Symfony\Component\HttpKernel\Exception\HttpException(404);
}