MichaelDeBoey
MichaelDeBoey

Reputation: 2385

Catch custom Exception in Silex isn't working as expected

I'm making an application in Silex.

Somewhere in my code I do throw new OrderNotFoundException($message, 404);

So the $app->error in my index.php will catch this. I've implemented this as followed:

$app->error( function ( \Exception $e, $code ) use ( $app ) {
    $messages = [ ];

    switch ($code) {
        case 401:
            $messages[ 'message' ] = 'unauthorized';
            break;
        case 404:
            if($e instanceof OrderNotFoundException){
                $messages[ 'message' ] = 'no_order_found';
            } else {
                $messages[ 'message' ] = 'page_not_found';
            }
            break;
        case 409:
            if($e instanceof MultipleOrderException){
                $messages[ 'message' ] = 'multiple_orders';
            }
            break;
        default:
            $messages[ 'message' ] = 'unknown_error';
    }

    return $app[ 'twig' ]->render( 'home.twig', $messages );
} );

But I keep getting the 'unknown_error'.
Is the $code that I throw with my exception passed correctly or should I do this another way?

Making an new Error-function for every Exceptions seems not the good way I think.

Upvotes: 0

Views: 281

Answers (2)

DarkBee
DarkBee

Reputation: 15619

Imho you would be better of doing it this like :

$app->error( function (OrderNotFoundException $e, $code ) use ( $app ) {

});


$app->error( function (MultipleOrderException $e, $code ) use ( $app ) {

});

//...

$app->error( function (Exception $e, $code ) use ( $app ) {


});

Upvotes: 1

Federkun
Federkun

Reputation: 36964

OrderNotFoundException should implement HttpExceptionInterface. In this case you can extend NotFoundHttpException:

use Symfony\Component\HttpKernel\NotFoundHttpException;

class OrderNotFoundException extends NotFoundHttpException {}

and just throw the exception with

throw new OrderNotFoundException($message);

Upvotes: 1

Related Questions