2
votes

I'm trying to set up a smart error catching system in Laravel so I can define a view for every error instead of the traditional "Something went wrong here." message with debugging off. I've successfully caught typical http headers such as 404, 403, 405, and 500 however now I would like the catch the ModelNotFoundException and simply return 404. Here's what I've got so far:

App::error(function(Exception $e, $code) {

  $error = ['code' => $code];

  switch($code) {

    case 403:

      return Response::view('errors.error', $error, $code);

    break;

    case 404:

      return Response::view('errors.error', $error, $code);

    break;

    case 405:

      return Response::view('errors.error', $error, $code);

    break;

    case 500:

      return Response::view('errors.error', $error, $code);

    break;

    default:

      return;

    break;

  }

    /*  
      | Returns null if the error is not 401, 403, 404, 500, 405
      | I just have a default of null in the switch on $code.

      if(!in_array($code, [401, 403, 404, 500, 405])) {

        return;  

      }

    */


});


App::error(function(ModelNotFoundException $e) {

  return Response::view('errors.error', ['code' => 404], 404);

});

Now detecting the 403, 404, 405, 500 headers works perfect however when I added another App::error to listen for ModelNotFoundException's, all fails. For every exception I am returned null. By default, a 500 header is thrown by ModelNotFoundException and that is what is displayed in my view. I want it to be a 404.

TL;DR

  • I would like ModelNotFoundException to throw 404 instead of 500.
2

2 Answers

13
votes

First you need a 404.blade.php file in views/errors directory.
Here is how to throw a 404 error when a ModelNotFoundException occurs:

Laravel 4
In app/start/global.php

App::error(function(Illuminate\Database\Eloquent\ModelNotFoundException $exception, $code)
{
    return Response::view('errors.404', array(), 404);
});

Laravel 5.0 & 5.1
Add this code to render() method in /app/exceptions/handler.php :

if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
    return response()->view('errors.404', array(), 404);
}

Laravel 5.2+
A 404 error is automatically returned when a ModelNotFound exception occurs.

3
votes

Resolved--the issue was namespacing. The correct namespace for the exception was:

\Illuminate\Database\Eloquent\ModelNotFoundException