【问题标题】:How can I universally handle an exception with a certain property in Laravel?如何在 Laravel 中普遍处理具有特定属性的异常?
【发布时间】:2017-02-04 00:02:42
【问题描述】:

我想在

中创建类似于unauthenticated() 函数的东西

app\Exceptions\Handler.php

但我的例外是 Guzzle 生成的包含特定 http 代码和 json 正文的例外。

我已经有一个可以像这样工作的辅助类:

  public static function get($enum) {
        $headers = self::headers();
        $client = new Client();
        try {
            $response = $client->request('GET', config('app.apiurl') . '/api/' . $enum, ['headers' => $headers]);
        } catch (\Exception $e) {
            $response = $e->getResponse();
            $body = json_decode($response->getBody(), true);
            $code = $response->getStatusCode();

           if ($body['code'] == 101 && $code == 412) {
               throw new \Exception("wizard eerst", 101);
           }
        }

但我更喜欢在通用处理程序中执行此操作,例如某种用于异常的中间件。所以我不想尝试捕获每个调用,而是捕获所有符合我描述的异常并通过重定向处理它们。

解决方案

public function render($request, Exception $exception) {

$response = $exception->getResponse();
$body = json_decode($response->getBody(), true);
$code = $response->getStatusCode();

if ($body['code'] == 101 && $code == 412) {
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Je moet eerst de profielwizard afmaken'], $code);
    }

    return redirect('/wizard');
}

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

【问题讨论】:

  • @GiamPy 不是,我描述过我想用另一种方式处理它,我已经成功地实现了这种方式。

标签: laravel exception exception-handling guzzle


【解决方案1】:

app\Exceptions\Handler.php 中存在一个render 函数。

要处理不同类型的Exception,可以尝试:

public function render($request, Exception $e)
{
    if ($e instanceof SomeTypeException1)
    {
        #handle it
    }
    else if($e instanceof SomeTypeException2)
    {
        #handle it
    }

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2016-01-07
    • 2015-09-15
    • 2016-11-22
    • 2018-11-30
    相关资源
    最近更新 更多