Php 捕获ValidationException时返回自定义json响应
我有一个控制器入口点,在这里我从我的ProductService中execute另一个方法在一个try-catch块中,我假装捕获$this->ProductService->create()方法中可能发生的所有异常,除了验证错误,如果是验证错误$e->getMessage()将不起作用,因为我将得到一般响应“给定数据无效”,而不是完整的自定义消息。在阅读了一些之后,我决定在laravel处理程序类中使用render方法,我添加了以下内容:Php 捕获ValidationException时返回自定义json响应,php,laravel,Php,Laravel,我有一个控制器入口点,在这里我从我的ProductService中execute另一个方法在一个try-catch块中,我假装捕获$this->ProductService->create()方法中可能发生的所有异常,除了验证错误,如果是验证错误$e->getMessage()将不起作用,因为我将得到一般响应“给定数据无效”,而不是完整的自定义消息。在阅读了一些之后,我决定在laravel处理程序类中使用render方法,我添加了以下内容: //In order to react to vali
//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,因为它应该是422,这就是为什么在我的render方法中我手动返回422。在我的try catch块中,有正常异常$e->getCode()正常工作,为什么会这样?在渲染函数中,您引用的是未定义的错误实例,您定义了Exception$Exception,但您引用的是$e->errors() 您的代码应该是:
public function render($request, Exception $exception)
{
if ($request->ajax() && $exception instanceof ValidationException) {
return response()->json([
'message' => $exception->errors(),
],422);
}
return parent::render($request, $exception);
}
将$e->errors();更改为$exception->errors();在渲染函数中,您正在引用未定义的错误实例,您已经定义了exception$exception,但您正在引用$e->errors() 您的代码应该是:
public function render($request, Exception $exception)
{
if ($request->ajax() && $exception instanceof ValidationException) {
return response()->json([
'message' => $exception->errors(),
],422);
}
return parent::render($request, $exception);
}
将$e->errors();更改为$exception->errors();这一点您是对的,但我仍然无法获取验证失败的处理程序方法…您是对的,但我仍然无法获取验证失败的处理程序方法。。。