Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silex: error handlers for specific exception types

It it possible in Silex to use an error handler based on what exception is thrown?

I know this is possible with a single exception handler and a switch statement on the classname of the thrown exception but to me it seems the "Silex way" is cleaner, yet doesn't work.

This is how I would expect it to work

<?php
// Handle access denied errors
$app->error(function (\App\Rest\Exception\AccessDenied $e) {
    $message = $e->getMessage() ?: 'Access denied!';
    return new Response($message, 403);
});
// Handle Resource not found errors
$app->error(function (\App\Rest\Exception\ResourceNotFound $e) {
    $message = $e->getMessage() ?: 'Resource not found!';
    return new Response($message, 404);
});
// Handle other exception as 500 errors
$app->error(function (\Exception $e, $code) {
    return new Response($e->getMessage(), $code);
});

Problem is that when I throw a ResourceNotFound exception in my controller, the errorhandler tied to AccessDenied is executed

Catchable fatal error: Argument 1 passed to {closure}() must be an instance of App\Rest\Exception\AccessDenied, instance of App\Rest\Exception\ResourceNotFound given

Is this achievable in another way or should I just stuff everything in the handler that works with generic Exceptions and switch on the type of exception thrown?

PS: i'm aware of the $app->abort() method but prefer working with exceptions

like image 271
ChrisR Avatar asked Mar 23 '12 14:03

ChrisR


1 Answers

EDIT: This feature has now made it into Silex core!


This is currently not possible. Right now you'd have to either have a single handler with a switch statement, or many handlers with an if ($e instanceof MyException) each.

I do like the idea though, and it should be possible to implement it by using reflection. It would be awesome if you could create a new ticket on the tracker, or even work on a patch, if you're interested.

Cheers!

like image 100
igorw Avatar answered Nov 01 '22 11:11

igorw