【问题标题】:How to set a 'plain' exception handler in Laravel 4如何在 Laravel 4 中设置“普通”异常处理程序
【发布时间】:2014-05-04 22:21:55
【问题描述】:

Laravel 4.1 中,当抛出和调试中的异常设置为false 时,会显示普通异常。

消息大致如下:

哎呀,出事了

我浏览了代码,似乎普通异常处理程序注册在:

Illuminate\Exception\ExceptionServiceProvider.php

通过以下行

protected function registerHandler()
{
    $this->app['exception'] = $this->app->share(function($app)
    {
        return new Handler($app, $app['exception.plain'], $app['exception.debug']);
    });
}

在哪里设置我自己的自定义普通处理程序?我不喜欢“哎呀”消息,我希望能够显示特定于站点的消息

干杯

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    这是普通的异常处理程序;默认情况下已在 app/start/global.php 中提供,修改如下(顺便说一句,Whoops! PHP Errors only for Cool Kids):

    App::error(function(Exception $exception)
    {
        Log::error($exception);Log::error($exception->getMessage());
        return View::make('errors.index')->with('exception', $exception);
    });
    

    创建视图view/errors/index.blade.php

    @extends('layouts.master')
    
    @section('content')
    
        <div class="page-header">
            <h1>Oops!</h1>
        </div>
    
        <div class='well'>ERROR: {{ $exception->getMessage() }}</div>
    
    @stop
    

    同时在你的app/config/app.php 文件中创建'debug' =&gt; false

    /*
    |--------------------------------------------------------------------------
    | Application Debug Mode
    |--------------------------------------------------------------------------
    |
    | When your application is in debug mode, detailed error messages with
    | stack traces will be shown on every error that occurs within your
    | application. If disabled, a simple generic error page is shown.
    |
    */
    
    'debug' => false,
    

    您可以在$exception 对象中使用以下方法:

    array (size=10)
      //0 => string '__construct' (length=11)
      1 => string 'getSeverity' (length=11)
      2 => string 'getMessage' (length=10)
      3 => string 'getCode' (length=7)
      4 => string 'getFile' (length=7)
      5 => string 'getLine' (length=7)
      6 => string 'getTrace' (length=8)
      7 => string 'getPrevious' (length=11)
      8 => string 'getTraceAsString' (length=16)
      //9 => string '__toString' (length=10)
    

    如果您离开'debug' =&gt; true,,那么您的异常处理程序仍然可以工作,但在某些情况下,当异常未在您的处理程序中捕获但在通用Exception 处理程序之前的另一个特定处理程序中时,它可能会显示whoops

    还请记住,Exception 类是最通用的异常类型,如果您在此之后定义了其他更具体的异常处理程序,那么如果从该特定处理程序返回任何响应,它将不会被触发。

    【讨论】:

    • 人几乎太容易了,但不能从答案中带走。谢谢@WereWolf - Alpha
    【解决方案2】:

    在你的 app/start/global.php 文件中添加

    App::missing(function($exception)
    {
        return 'Your custom message'; // you can also specify a view to render.
    });
    

    请访问http://laravel.com/docs/errors了解更多信息

    【讨论】:

    • 我相信只处理 404。我正在寻找所有其他异常。通常捕获在 App::error(function(Exception $exception, $code) { Log::error($exception); });
    猜你喜欢
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    相关资源
    最近更新 更多