在我的Laravel5.5项目中,视图合成器用于将数据传递给视图。
在视图编写器的constructor()中,使用try catch块捕获异常,并从catch方法重新抛出自定义异常。
在应用程序的默认异常处理程序中,将处理自定义异常以显示我的自定义错误视图。
问题:自定义异常在从视图编写器抛出时不能正常工作。将显示Laravel的默认异常错误页,而不是我的自定义错误页。
ProductComponentComposer.php
namespace App\Http\ViewComposers;
use Illuminate\View\View;
use App\Repositories\ProductRepository;
use Exception;
use App\Exceptions\AppCustomException;
class ProductComponentComposer
{
protected $products;
/**
* Create a new product partial composer.
*
* @param ProductRepository $productRepo
* @return void
*/
public function __construct(ProductRepository $productRepo)
{
try {
$this->products = $productRepo->getProducts();
} catch (Exception $e) {
throw new AppCustomException("CustomError", 1001);
}
}
/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$view->with(['productsCombo' => $this->products]);
}
}Handler.php
public function render($request, Exception $exception)
{
if($exception instanceof AppCustomException) {
//custom error page when custom exception is thrown
return response()->view('errors.app-custom-exception', compact('exception'));
}
return parent::render($request, $exception);
}注意:如果从控制器抛出,则会正确处理自定义异常。
我还尝试从ProductComponentComposer的compose()方法而不是__constructor()抛出异常。但这也行不通。
如何修复此以获得自定义异常视图(如果视图编写器中发生任何异常)?
提前谢谢..。
发布于 2019-10-04 10:05:48
在视图编写器类中的方法中抛出自定义异常时,我也遇到了同样的问题,但是显示的是\ErrorException。框架级别(\laravel\framework\src\Illuminate\View\Engines\PhpEngine.php:45)上有一个处理程序,我认为是造成这种情况的原因。
修正了我的申请:
App\Exceptions\Handler.php
public function render($request, Exception $exception)
{
if ($exception instanceof AppCustomException ||
$exception instanceof \ErrorException &&
$exception->getPrevious() instanceof AppCustomException
) {
//custom error page when custom exception is thrown
return response()->view('errors.app-custom-exception', compact('exception'));
}
// default
return parent::render($request, $exception);
}确保你得到的是\ErrorException的一个实例
https://stackoverflow.com/questions/50969553
复制相似问题