【问题标题】:Handling a non-fatal exception in Laravel在 Laravel 中处理非致命异常
【发布时间】:2014-10-30 11:07:47
【问题描述】:

在我的 laravel 应用中,假设我有一段代码如下,作为示例

function convert_amount($amount, $currency, $date)
{
    if (strlen($currency) <> 3)
    {
        // Exception thrown
    } else {
        // convert $amount from $currency on $date
    }
    return $amount;
}

在这里,我只是将数字从货币转换为基数。我执行一个简单的检查以查看传递的货币字符串是否为 3 个字符,以确保它是 ISO 货币代码(欧元、英镑、美元等)。如果不是,我想抛出异常,但不会导致应用程序掉入错误页面,就像 Laravel 的错误处理程序经常出现的情况一样。

相反,我想继续处理页面,但记录异常,并可能在 Flash 消息中显示错误。 有没有我可以为 Laravel 定义的监听器来实现这一点?我是否需要定义一个新的异常类型NonFatelException 或许这就是逻辑。

编辑

基本上,我想我可以像这样注册一个新的异常处理程序:

class NonFatalException extends Exception {}

App::error(function(NonFatalException $e)
{
    // Log the exception
    Log::error($e);
    // Push it into a debug warning in the session that can be displayed in the view
    Session::push('debug_warnings', $e->getMessage());
});

然后在我的应用程序中的某个地方:

throw new NonFatalException('Currency is the wrong format. The amount was not converted');

这样做的问题是默认的异常处理程序将被调用,从而导致错误页面而不是将要到达的页面。 我可以在我的处理程序中返回一个值来避免默认值,但我相信这会导致仅显示该返回值并且我的其余脚本将不会运行。

【问题讨论】:

  • 为什么不直接使用try .. catch ...?
  • 将其放入 try catch 并在 catch 块中使用 Log::error('This is an error.');
  • 使用 Laravel 的错误处理程序不是更好吗 - 我想在应用程序的许多区域实现相同的行为,而不仅仅是这个简单的功能。
  • 这只是一个验证错误。
  • OK 所以不值得例外?

标签: php exception laravel exception-handling


【解决方案1】:

你走在正确的道路上。为什么不使用try...catch tho?

您的辅助方法将是:

function convert_amount($amount, $currency, $date)
{
    if (strlen($currency) <> 3)
    {
        throw new NonFatalException('Currency is the wrong format. The amount was not converted');
    } else {
        // convert $amount from $currency on $date
    }
    return $amount;
}

无论何时使用它,请将其放入try...catch

try {
   convert_amount($amount, $currency, $date);
} catch (NonFatalException $e) {
   // Log the exception
   Log::error($e);
   // Push it into a debug warning in the session that can be displayed in the view
   Session::push('debug_warnings', $e->getMessage());
}

这样,您的应用将永远不会停止,并且您会在 Session 中看到错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    相关资源
    最近更新 更多