php - 捕获 ValidationException 时返回自定义 json 响应
问题描述
我有一个控制器入口点,我在其中从我的 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 块中正常工作,这是为什么呢?
解决方案
在您的渲染函数中,您引用了一个未定义的错误实例,您定义了 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();
推荐阅读
- xslt - how do I nest elements dynamically using XSLT?
- regex - 在 Perl 中,如何匹配两个连续的回车符?
- python - 为什么我的代码无法从谷歌加载 MNIST 数据集?
- python-3.x - Python requests.get(url) 返回 javascript 代码而不是页面 html
- opengl - libgdx:渲染带有纹理的模型,看起来褪色
- graphql - 使用常规 GraphQL 查询复制 graphQL 自省查询以避免安全风险(同时使用 graphql-compose-mongoose)
- django - 为什么在 Django 中的索引处保存查询集元素不起作用?
- windows - 使用存档获取“格式错误:找不到 EOCD 签名”
- vb6 - 如何确保在 vb 6 中任何时候打开的表单实例都不超过一个?
- python-2.7 - Python中的检查按钮条件