Laravel自定义异常给了我未定义的属性:: $ headers

时间:2018-12-06 17:20:31

标签: laravel laravel-5

我现在正在laravel中处理一个异常,这种异常行为是我以前从未见过的,而且似乎找不到太多的信息。我收到此错误消息未定义的属性:App \ Exceptions \ UserNotApproved :: $ headers。不知道怎么回事。

<?php

namespace App\Exceptions;

use Exception;

class UserNotApproved extends Exception
{
    /**
     * 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 the exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function render($request)
    {
        return response()->view('errors.not_approved',['exception'=>$this],403);
    }
}


/var/www/epg_intranet/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php

$ response-> headers-> setCookie在第159行

<?php

namespace App\Http\Middleware;

use App\Exceptions\UserNotApproved;
use App\User;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class VerifyUserApproval
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check() && Auth::user()->user_type == null){
            return new UserNotApproved();
        }
        return $next($request);
    }
}

我在中间件中称呼它。错误会导致什么?

1 个答案:

答案 0 :(得分:0)

public function handle($request, Closure $next)
{
    if (Auth::check() && Auth::user()->user_type == null){
        return new UserNotApproved();
    }
    return $next($request);
}

一个中间件应该接收一个响应,查看它并做一些事情,然后返回一个响应,以便下一个中间件也可以完成它的工作。由于下一个中间件未接收到请求对象,因此返回UserNotApproved类会引发此错误。

您可以执行以下操作:

public function handle($request, Closure $next) {
    if (Auth::check() && Auth::user()->user_type == null) {
        abort(400, 'User not approved.');
    }
    return $next($request);
}

您也许也可以这样做

public function handle($request, Closure $next) {
    if (Auth::check() && Auth::user()->user_type == null) {
        throw new UserNotApproved();
    }
    return $next($request);
}