在我的 laravel 5.5 项目中,视图编辑器用于将数据传递给视图 .

view composerconstructor() 中, try catch 块用于捕获异常,并使用catch方法中的 custom exception is rethrown .

在应用程序的默认异常处理程序中,处理自定义异常以显示我的自定义错误视图 .

Problem : 从视图编辑器中抛出时,自定义异常无法正常工作 . 显示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);
    }

Note : 如果从控制器抛出自定义异常,则会正确处理 .

我也尝试从 ProductComponentComposercompose() 方法而不是 __constructor() 中抛出异常 . 但那也行不通 .

How to fix this 获取我的自定义异常视图,如果视图编辑器中发生任何异常?

提前致谢..