【问题标题】:Laravel throw ValidationException but not hitting destroy method's catch block?Laravel 抛出 ValidationException 但没有击中破坏方法的 catch 块?
【发布时间】:2020-04-26 22:41:39
【问题描述】:

我正在尝试使用 Laravel 的 ValidationException 类返回自定义异常消息。我在以下示例中成功运行:

public function store(Request $request)
{
    $this->validate($request, CurrencyValidatorArrays::$store);
    try {
        $this->currenciesInstance->createOrUpdateCurrency($request->all());

        return redirect()->route('currencies.index')
        ->with('success', 'Successfully created currency');
    } catch (Exception $e) {

        return redirect()->route('currencies.create')
        ->with('error', $e->getMessage());
    }
}

createOrUpdateCurrency() 中引发异常的位置

    if(Currency::where('position', $data['position'])->where('id', '!=', $id)->exists()) {

        throw ValidationException::withMessages([
            'error' => ['Position value is already taken']
         ]);
    }

然后这会将异常消息传递回我的视图以进行显示。

但是,当我尝试删除一家公司时,我正在尝试在其他地方实现这一点,我首先检查没有用户存在:

public function destroy($id)
    {
        try {

            $this->companiesInstance->deleteCompany($id);

            return redirect()->route('companies.index')
            ->with('success', 'Successfully deleted company');

        } catch (Exception $e) {

            return redirect()->route('companies.index')
            ->with('error', $e->getMessage());
        }
    }

deleteCompany()内部:

$company = Company::find($id);
if($company->users()->exists()){
    throw ValidationException::withMessages([
        'error' => ['Position value is already taken']
     ]);
}

由于某种原因,这不会从主销毁方法中命中我的 catch 块,如果我将异常类型从 Exception 更改为 ValidationException,我可以访问并查看异常对象,但不能以我可以的方式Store() 方法版本。有什么想法吗?

更新:

所以我有一些解决方法:

解决我使用的异常类型问题:

catch (ValidationException | Exception $e) { ...

但这在访问异常消息时仍然无济于事,因为当它是 ValidationException 类型时,默认构造函数验证消息是从 getMessage() 返回的,而不是我指定的。

【问题讨论】:

  • 嗨,我注意到,来自 Laravel 的开箱即用的 ValidationException 实例不允许您有足够的时间来捕获异常,因为它会在您执行任何操作之前重定向。看看下面的链接。 stackoverflow.com/questions/31217541/…

标签: php laravel


【解决方案1】:

PHP 7 处理异常的方式略有不同。你可以阅读它here

回到您的代码,您必须尝试捕获 Throwable 对象而不是 Exception。

try
{
   // Code that may throw an Exception or Error.
}
catch (Throwable $t)
{
   // Code that handles the error
}

希望这会有所帮助。

【讨论】:

  • 似乎没有解决这个问题,主要问题是 ValidationException 可以作为存储中的标准异常处理,但不能作为 destroy() 处理。 :(
  • 您确定异常是由您的代码在 deleteCompany() 中引发的吗?您可以尝试在实际抛出异常之前创建异常并转储它吗?
猜你喜欢
  • 1970-01-01
  • 2019-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
相关资源
最近更新 更多