laravel - Inertiajs - Laravel:如何抛出自定义错误
问题描述
怎么可能在 Inertiajs.vue 中从 Laravel 抛出自定义错误而不重定向呢?
Vue 组件:
Inertia.post('company-organisations-create', {
name: this.newOrganisation.name,
description: this.newOrganisation.description
},
{
preserveScroll: true,
onSuccess: (page) => {
return Promise.all([
window.Toast.success(this.$page.props.toast.message),
this.newOrganisation.name = '',
this.newOrganisation.description = '',
])
},
onError: (errors) => {
window.Toast.error(errors.toastMessage)
}
});
Laravel 控制器():
public function createOrganisations(Request $request)
{
try {
CompanyOrganisations::create([
'company_id' => $companyID,
'name' => $orgName,
'description' => $orgDescription,
]);
} catch(Excpetion) {
// Create Inertia Error 'onError'
/* As example with json response
return response()->json([
'message' => 'ups, there was an error',
], 403); */
}
return Redirect::route('company.organisations',
)->with([
'toastMessage' => 'Organization created!'
]);
}
由于我无法在 Inertia 请求中接收 json 格式,我需要在 Inertiajs.vue 组件中抛出错误。
非常感谢你。
解决方案
试试这个:
try {
// ...
} catch(Excpetion) {
return redirect()->back()->withErrors([
'create' => 'ups, there was an error'
])
}
应该收到错误onError
onError: (errors) => {
window.Toast.error(errors.create)
}
推荐阅读
- vue.js - 无法从异步函数结果中显示
- android - Google Mobile vision api:如何检测和跟踪超过 3 个 QR 码?
- python - 从元组中获取替代值
- java - 从图库中选择多个图像显示一些错误
- node.js - 使用passport-jwt登录后未授权
- multithreading - 如何使双重汇总统计线程安全?
- asp.net - 如何使用 ASP.Net 中的会话变量从母版页加载功能中删除 html 链接?
- c++ - 为什么没有调用复制构造函数?
- android - 快速 Android 网络 cookie 问题
- android - 无法在 Android Studio 中创建新活动(发生 IDE 错误)