Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching error exceptions in Laravel 4

From the documentation it says we can catch all 404 like so:

App::missing(function($exception)
{
    return Response::view('errors.missing', array(), 404);
});

And we can also do things like:

App::abort(404);
App::abort(403);

All 404 gets handled by the App::missing

All other errors gets handled by:

App::error(function( HttpException $e)
{
    //handle the error
});

But the question is How do i handle each of the error like if its a 403 I will display this if its a 400 I will display another error

like image 748
majidarif Avatar asked Dec 30 '13 08:12

majidarif


1 Answers

Short answer: if your custom App::error function does not return a value, Laravel will handle it. Check the docs

Code sample for custom error views and/or logic:

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

    // Careful here, any codes which are not specified
    // will be treated as 500

    if ( ! in_array($code,array(401,403,404,500))){
       return;
    }

    // assumes you have app/views/errors/401.blade.php, etc
    $view = "errors/$code";

    // add data that you want to pass to the view
    $data = array('code'=>$code);

    // switch statements provided in case you need to add
    // additional logic for specific error code.

    switch ($code) {
       case 401:
       return Response::view($view, $data, $code);

       case 403:
       return Response::view($view, $data, $code);

       case 404:
       return Response::view($view, $data, $code);

       case 500:
       return Response::view($view, $data, $code);

   }

});

The above snippet could be inserted in app/start/global.php after the default Log::error handler, or better yet in the boot method of a custom service provider.

EDIT: Updated so the handler only processes codes you specify.

like image 148
Makita Avatar answered Oct 18 '22 07:10

Makita