2014-10-30 81 views
0

非致命的异常在我laravel的应用程序,说我有一些代码如下,作为一个例子处理在Laravel

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

在这里,我简单地从一种货币转换号码的基础。我执行一个简单的检查,看看货币字符串是否为3个字符以确保它是ISO货币代码(EUR,GBP,USD等)。如果没有,我想抛出一个异常,但不会导致应用程序掉到错误页面,就像Laravel的错误处理程序经常出现这种情况。

相反,我想继续处理页面,但记录异常并可能在闪存消息中显示错误。 有没有可以为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'); 

这种麻烦的是那么将会调用默认的异常处理程序,从而导致错误页面而不是将要到达的页面。 我可以在我的处理程序中返回一个值以避免默认值,但我相信这会导致只显示返回值,而其余的脚本将不会运行。

+1

为什么不使用'try .. catch' ...? – Carpetsmoker 2014-10-30 11:10:19

+0

把它放在try catch中并使用'Log :: error('这是一个错误。');'在catch块中。 – itachi 2014-10-30 11:11:46

+0

使用Laravel的错误处理程序会不会更好 - 我想在应用程序的许多方面实现相同的行为,而不仅仅是这个简单的函数。 – harryg 2014-10-30 11:13:01

回答

0

你是在一条正确的道路上。为什么不使用try...catch寿?

你的helper方法是:

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

这样,你的应用程序将永远不会STOPP,你有会话中的错误消息。