首页 > 解决方案 > 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 组件中抛出错误。

非常感谢你。

标签: laravelvue.jsinertiajs

解决方案


试试这个:

try {
// ...
} catch(Excpetion) {
   return redirect()->back()->withErrors([
      'create' => 'ups, there was an error'
   ])
}           

应该收到错误onError

onError: (errors) => {
   window.Toast.error(errors.create)
}

推荐阅读