2016-04-26 64 views
1

我正尝试使用自定义参数创建自定义异常。我觉得我在这里做错了事。基本上我想处理Laravel的异常处理文件中的异常,但我需要额外的数据,例外情况是要知道是谁引起异常。这是我到目前为止...Laravel 5.1自定义异常的自定义参数

<?php 

namespace App\Exceptions; 

use Exception; 

class ApiException extends \Exception 
{ 
    public $userId; 

    public function __construct($userId, $message, $code, Exception $previous) 
    { 
     parent::__construct($message, $code, $previous); 
     $this->userId = $userId; 
    } 

} 

这里的想法是将userId传递到异常,以便我可以稍后访问它。但我有问题。在这种情况下,我不知道要通过什么作为“$前一个”变量...

throw new ApiException($user->id, 'im testing', 200, $previous); 

任何帮助将不胜感激。

回答

2

看到这个documentation上异常

前面的变量用于异常链并具有NULL默认值。您可以将其添加到您的扩展。

<?php 

namespace App\Exceptions; 

use Exception; 

class ApiException extends \Exception 
{ 
    public $userId; 

    public function __construct($userId, $message, $code, Exception $previous = NULL) 
    { 
     parent::__construct($message, $code, $previous); 
     $this->userId = $userId; 
    } 

} 

这样您可以继续支持异常链接,如果将来需要它,但不会在每次抛出ApiException时都要求它。