在Laravel 5.3中创建自定义异常类和自定义处理程序类 [英] Creating a custom exception class and custom handler class in Laravel 5.3

查看:471
本文介绍了在Laravel 5.3中创建自定义异常类和自定义处理程序类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我得到代码之前,让我解释一下我的目标。我的网络应用程序显示出售车辆。我需要一个自定义的404页面,如果用户尝试访问不存在的页面,则会显示12个添加到数据库中的最新车辆。



我有以下...



App \Exceptions\CustomException.php

 <?php 

命名空间App \Exceptions;

使用异常;

class CustomException extends Exception
{
public function __construct()
{
parent :: __ construct();
}
}

App \Exceptions\CustomHandler.php



 <?php 
命名空间App \Exceptions;

使用异常;
使用App \Exceptions\Handler作为ExceptionHandler;
使用Illuminate\Contracts\Container\Container;
使用App \Project\Frontend\Repo\Vehicle\EloquentVehicle;
使用Illuminate\Foundation\Exceptions\Handler;
使用Illuminate\Support\Facades\View;

class CustomHandler extends ExceptionHandler
{
protected $ vehicle;

public function __construct(Container $ container,EloquentVehicle $ vehicle)
{
parent :: __ construct($ container);

$ this->车辆= $车辆;
}

/ **
*报告或记录异常。
*
*这是向Sentry,Bugsnag等发送异常的好地方。
*
* @param \Exception $ exception
* @return void
* /
public function report(Exception $ exception)
{
parent :: report($ exception);
}

/ **
*向HTTP响应中呈现异常。
*
* @param \Illuminate\Http\Request $ request
* @param \Exception $ exception
* @return \Illuminate\Http\响应
* /
public function render($ request,Exception $ exception)
{
$ exception = Handler :: prepareException($ exception);

if($ exception instanceof CustomException){
return $ this-> showCustomErrorPage();
}

return parent :: render($ request,$ exception);
}

public function showCustomErrorPage()
{
$ recentAdded = $ this-> vehicle-> fetchLatestVehicles(0,12);

return View :: make('errors.404Custom') - > with('recentAdded',$ recentAdded);
}
}

为了测试这个我添加了


将新的CustomException();


给我的控制器,但它不提出404自定义视图。我需要做些什么才能使这项工作有效?



更新如果您尝试使用以下方式访问课程中的函数,则会得到BindingResolutionException:



应用程序(MyClass :: class) - > functionNameGoesHere ();



要简单地创建一个变量,就像将你的类绑定到服务提供者的容器一样。



我的代码如下所示:

  protected function showCustomErrorPage()
{
$ eloquentVehicle = new EloquentVehicle(new Vehicle(),new Dealer());
$ recentAdded = $ eloquentVehicle-> fetchLatestVehicles(0,12);

return view() - > make('errors.404Custom') - > with('recentAdded',$ recentAdded);
}

Amit的版本

  protected function showCustomErrorPage()
{
$ recentAdded = app(EloquentVehicle :: class) - > fetchLatestVehicles(0,12);

return view() - > make('errors.404Custom') - > with('recentAdded',$ recentAdded);
}


解决方案

Laravel调用 render 函数 App \Exceptions\Handler class。所以重写它将不起作用。



你必须将它添加到 App \Exceptions\Handler



例如:

 <?php 

命名空间App \Exceptions;

使用异常;
使用Illuminate\Auth\AuthenticationException;
使用App \Project\Frontend\Repo\Vehicle\EloquentVehicle;
使用Illuminate\Foundation\Exceptions\Handler作为ExceptionHandler;

class Handler extends ExceptionHandler
{
/ **
*不应该报告的异常类型的列表。
*
* @var数组
* /
protected $ dontReport = [
\Illuminate\Auth\AuthenticationException :: class,
\\ \\Illuminate\Auth\Access\AuthorizationException :: class,
\Symfony\Component\HttpKernel\Exception\HttpException :: class,
\Illuminate\Database\ Eloquent\ModelNotFoundException :: class,
\Illuminate\Session\TokenMismatchException :: class,
\Illuminate\Validation\ValidationException :: class,
];

/ **
*报告或记录一个例外。
*
*这是向Sentry,Bugsnag等发送异常的好地方。
*
* @param \Exception $ exception
* @return void
* /
public function report(Exception $ exception)
{
parent :: report($ exception);
}

/ **
*向HTTP响应中呈现异常。
*
* @param \Illuminate\Http\Request $ request
* @param \Exception $ exception
* @return \Illuminate\Http\响应
* /
public function render($ request,Exception $ exception)
{
if($ exception instanceof CustomException){
return $ this-> showCustomErrorPage ();
}

return parent :: render($ request,$ exception);
}

protected function showCustomErrorPage()
{
$ recentAdded = app(EloquentVehicle :: class) - > fetchLatestVehicles(0,12);

return view() - > make('errors.404Custom') - > with('recentAdded',$ recentAdded);
}
}


Before I get to the code, let me explain my aim. My web app displays vehicles for sale. I have a need for a custom 404 page that will display 12 of the latest vehicles added to the database if the user tries to access a page that doesn't exist.

I have the following...

App\Exceptions\CustomException.php

<?php

namespace App\Exceptions;

use Exception;

class CustomException extends Exception
{
    public function __construct()
    {
        parent::__construct();
    }
}

App\Exceptions\CustomHandler.php

<?php
namespace App\Exceptions;

use Exception;
use App\Exceptions\Handler as ExceptionHandler;
use Illuminate\Contracts\Container\Container;
use App\Project\Frontend\Repo\Vehicle\EloquentVehicle;
use Illuminate\Foundation\Exceptions\Handler;
use Illuminate\Support\Facades\View;

class CustomHandler extends ExceptionHandler
{
    protected $vehicle;

    public function __construct(Container $container, EloquentVehicle $vehicle)
    {
        parent::__construct($container);

        $this->vehicle = $vehicle;
    }

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        $exception = Handler::prepareException($exception);

        if($exception instanceof CustomException) {
            return $this->showCustomErrorPage();
        }

        return parent::render($request, $exception);
    }

    public function showCustomErrorPage()
    {
        $recentlyAdded = $this->vehicle->fetchLatestVehicles(0, 12);

        return View::make('errors.404Custom')->with('recentlyAdded', $recentlyAdded);
    }
}

To test this I added

throw new CustomException();

to my controller but it doesn't bring up the 404Custom view. What do I need to do to get this working?

UPDATE: Just a note for anyone who's bound their class to their model. You'll get a BindingResolutionException if you try to access a function in your class using:

app(MyClass::class)->functionNameGoesHere();

To get around this simply create a variable in the same way you would bind your class to the Container in your service provider.

My code looks like this:

protected function showCustomErrorPage()
{
    $eloquentVehicle = new EloquentVehicle(new Vehicle(), new Dealer());
    $recentlyAdded = $eloquentVehicle->fetchLatestVehicles(0, 12);

    return view()->make('errors.404Custom')->with('recentlyAdded', $recentlyAdded);
}

Amit's version

protected function showCustomErrorPage()
{
    $recentlyAdded = app(EloquentVehicle::class)->fetchLatestVehicles(0, 12);

    return view()->make('errors.404Custom')->with('recentlyAdded', $recentlyAdded);
}

解决方案

Laravel calls the render function of App\Exceptions\Handler class. So overriding it will not work.

You have to add it in App\Exceptions\Handler class only.

For example:

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\AuthenticationException;
use App\Project\Frontend\Repo\Vehicle\EloquentVehicle;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Auth\Access\AuthorizationException::class,
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
        \Illuminate\Session\TokenMismatchException::class,
        \Illuminate\Validation\ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        if($exception instanceof CustomException) {
            return $this->showCustomErrorPage();
        }

        return parent::render($request, $exception);
    }

    protected function showCustomErrorPage()
    {
        $recentlyAdded = app(EloquentVehicle::class)->fetchLatestVehicles(0, 12);

        return view()->make('errors.404Custom')->with('recentlyAdded', $recentlyAdded);
    }
}

这篇关于在Laravel 5.3中创建自定义异常类和自定义处理程序类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆