在Laravel 4中捕获错误异常

时间:2013-12-30 08:48:44

标签: php error-handling laravel

从文档中我们可以像以下一样捕获所有404:

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

我们也可以这样做:

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

所有404都由App::missing

处理

所有其他错误都由以下方式处理:

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

但问题是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

1 个答案:

答案 0 :(得分:11)

简短回答:如果您的自定义App :: error函数没有返回值,Laravel将处理它。 Check the docs

自定义错误视图和/或逻辑的代码示例:

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);

   }

});

上面的代码段可以在默认的Log :: error处理程序之后插入app/start/global.php,或者更好地在自定义service provider的引导方法中插入。

编辑:已更新,因此处理程序仅处理您指定的代码。

相关问题