php - 收到 422 错误后,我无法在刀片中显示错误消息
问题描述
我对 laravel 中异常或错误处理的整个概念很陌生。基本上我有表单请求,当不满足规则时,会在控制台中显示 422 错误,我想将其转换为刀片中的错误消息,但我失败了。
我已经在 Exception/Handle.php 中尝试过
public function render($request, Exception $exception)
{
return redirect()->back()->with('error', 'Invalid data');
// return parent::render($request, $exception);
}
我在刀片中的错误消息应该适用于此:
@if(Session::has('error'))
<div class="alert alert-error">
{{ Session::get('error') }}
@php
Session::forget('error');
@endphp
</div>
@endif
我知道我应该在返回之前检查错误代码或实例,但我只想让它工作。我不能返回任何东西(根本没有回应)。一种认为哪个有效return parent::render($request, $exception);
,它会在控制台中显示错误消息
所以更多信息
我不知道它是否有帮助,但是请求是从 Vue 应用程序向控制器发出的,控制器以 FormRequest 作为参数。
另外,我无法检查错误代码,我试过了
public function render($request, Exception $exception)
{
if ($exception->getCode() === 422) {
return response([], 356); //should throw 356 error
}
return parent::render($request, $exception); // instead this return fires and gives me 422 error
}
Vue 组件
我的模板:
<template>
<form class="form" @submit.prevent="submit()">
<input type="text" class="form-control-plaintext textField"
placeholder="Post a comment" required v-model="textField">
<button :disabled="disabled" class="btn btn-success submit" type="submit">Post</button>
<button :disabled="disabled" class="btn btn-dark submit" type="reset">Cancel</button>
</form>
</template>
我的 axios 方法:
axios
.post('/comments', {
textField: this.textField,
id: this.id,
routeName: this.routename,
})
.then(response => {
this.name = '';
this.callReload(this.id);
this.textField = '';
})
.catch(function (error) {
console.log(error)
});
解决方案
您可能想要更改render
函数,我假设它是 fromApp\Exceptions\Handler.php
以返回JSON
通过JSON
.
public function render($request, $exception)
{
if ($request->isJson()) {
return response()->json(['error' => 'Error Detail'], 422);
}
}
您还需要检查exception
类型,而不是简单地为任何 JSON 异常返回 422 状态代码。
推荐阅读
- android - 如何使用 Expo 处理后台(应用程序关闭/手机休眠)通知?
- flutter - 颤振文本字段光标碎片问题
- php - WebSockets - 通过 php 发送 json 数据
- postgresql - 如何编写此 sql 查询以获取与会员参加的活动相关的lead.converteddate?
- php - 在 Laravel 中,它采用数据库中不可用的不同表行 ID
- bash - 如何在 bash 中设置动态地形计划?
- acumatica - 以编程方式创建时,销售订单中的税额未更新
- junit - (Junit5) 如何防止@BeforeEach 中的@AfterTest?
- c# - 如何克服以下错误:System.IO.IOException:'目录名称无效。在我的 foreach 循环中?
- python - 如果相关矩阵的值超出python中的阈值,如何在相关矩阵中获取行列对?