【发布时间】: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/…