samedi 21 avril 2018

Override exception in handler

I am using Route model binding using the id of a product and my route looks like this:

Route::get('product/{product}', ProductController@index');

I also have a custom ProductNotFoundException which I want to return when the route model binding only for this model fails to get the row (the row does not exist or is soft deleted.)

Any ideas how I could achieve that?

The two solutions I thought of are:

  1. Remove Route Model binding (obviously :P)
  2. Override the exception in the Exceptions/Handler

I chose to go with the second and do the following

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request $request
 * @param  \Exception               $exception
 *
 * @return \Symfony\Component\HttpFoundation\Response
 * @throws ProductNotFoundException
 */
public function render($request, Exception $exception)
{
    if ($exception instanceof ModelNotFoundException && $exception->getModel() === 'App\Models\Product') {
        throw new ProductNotFoundException();
    }

    return parent::render($request, $exception);
}

However, I am not sure whether is a good practice to throw an exception in the exception handler.

Can anyone see any other way or advice of the above solution?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Hhklet
via IFTTT

Aucun commentaire:

Enregistrer un commentaire