【发布时间】:2020-09-30 16:20:37
【问题描述】:
我有一个控制器入口点,在那里我从我的 ProductService 中执行另一个方法 inisde 一个 try catch 块,我假装捕获 $this->productServvice->create() 方法中可能发生的所有异常,但验证错误除外,如果这是一个验证错误 $e->getMessage() 不会做,因为我会得到通用响应“给定数据无效”而不是完整的自定义消息。在阅读了一些之后,我决定在 laravel Handler 类中使用 render 方法,我添加了这个:
//In order to react to validation exceptions I added some logic to render method, but it won't actually work, I'm still getting normal exception message returned.
public function render($request, Exception $exception)
{
if ($request->ajax() && $exception instanceof ValidationException) {
return response()->json([
'message' => $e->errors(),
],422);
}
return parent::render($request, $exception);
}
但是我仍然收到默认消息,这意味着我的 catch 块正在捕获正常异常,而不是我的自定义渲染方法...
在我的控制器中,try catch 块如下所示:
try
{
$this->productService->create($request);
return response()->json([
'product' => $product,
], 200);
}
//I want to catch all exceptions except Validation fails here, and return simple error message to view as
json
catch (\Exception $e)
{
return response()->json([
'message' => $e->getMessage(),
], $e->getStatus() );
}
另外,在 ValidationException 中,我不能使用 $e->getCode,$e->getStatus(),它总是返回 0 或 smetimes 1,afaik 它应该是 422,这就是为什么在我的渲染方法中我是手动的返回 422。在我的带有正常异常 $e->getCode() 的 try catch 块中正常工作,为什么会这样?
【问题讨论】: