在Laravel 4中捕获错误异常

maj*_*rif 5 php error-handling laravel

从文档中我们可以捕获所有404,如下所示:

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

我们还可以做以下事情:

App::abort(404);
App::abort(403);
Run Code Online (Sandbox Code Playgroud)

所有404都由.处理 App::missing

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

App::error(function( HttpException $e)
{
    //handle the error
});
Run Code Online (Sandbox Code Playgroud)

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

Mak*_*ita 11

简短回答:如果您的自定义App :: error函数没有返回值,Laravel将处理它.检查文档

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

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

   }

});
Run Code Online (Sandbox Code Playgroud)

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

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