user4748790
user4748790

Reputation:

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?

Upvotes: 0

Views: 99

Answers (1)

Brian Lee
Brian Lee

Reputation: 18197

Customize the binding resolution in RouteServiceProvider:

Route::bind('product', function ($value) { 
    $product = Product::find($value);
    if ($product === null) {
        throw new ProductNotFoundException();
    }
    return $product;
});

Explicit Model Binding

Upvotes: 1

Related Questions