在 Laravel 4 中捕获错误异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20836175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:49:33  来源:igfitidea点击:

Catching error exceptions in Laravel 4

phperror-handlinglaravel

提问by majidarif

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

从文档中它说我们可以像这样捕获所有 404:

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

所有 404 都由 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

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

回答by Makita

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

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

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.phpafter the default Log::error handler, or better yet in the boot method of a custom service provider.

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

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

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