laravel 如何在请求中捕捉服务器错误?

tmb3ates  于 2023-02-05  发布在  其他
关注(0)|答案(1)|浏览(111)

在laravel 8/inertiajs 0.10/vue 3中,我想捕获发生在服务器上的一些错误,如:

this.form.post(this.route('ads.store'), {
    preserveScroll: true,
    onSuccess: (p) => { // On succdess I see this message
        console.log('onSuccess p::')
        console.log(p)

        Swal.fire(
            'New Ad',
            'Your post has successfully been published!',
            'success'
        )
        this.form.description = null
    },
    onError: (p) => {  // That is not triggered!
        console.log('onError p::')
        console.log(p)
    }
})

受控:

public function store( AdFormRequest $request) {

    $data = $request->all();
    $data['status']= 'A';

    $ad = Ad::create($data);
    return $request->wantsJson()
        ? new JsonResponse($ad, 200)
        : back()->with('status', 'Error saving add');
}

因此,如果其中一个必填字段为空,我得到了laravel错误弹出窗口...如何捕捉它,并显示在www.example.com?Swal.fire ?

    • 修改编号1:**

在网上搜索我发现onError属性,但使:

this.deleteForm.delete(this.route('ads.destroy', this.nextAd), {
        preserveScroll: true,
        onError: (p) => { // THIS PART IS NOT CALLED ON ERROR
            console.log('onError p::')
            console.log(p)

            Swal.fire(
                'Delete Ad',
                'Error deleting ad!',
                'error'
            )
        },
        onSuccess:()=>{
            Swal.fire( // THIS PART IS CALLED ON SUCCESS
                'Delete Ad',
                'Your post has successfully been Delete!',
                'success'
            )
        }
    })

并控制:

public function destroy(Request $request, Ad $ad) {
    try {
        DB::beginTransaction();
        $ad->deleTTTte();

        DB::commit();
    } catch (QueryException $e) {
        DB::rollBack(); // I SEE THIS MESSAGE IN LOG FILE ON ERROR
        \Log::info( '-1 AdController store $e->getMessage() ::' . print_r( $e->getMessage(), true  ) );
        return $request->wantsJson()
            ? new JsonResponse($ad, 500 /*HTTP_RESPONSE_INTERNAL_SERVER_ERROR*/ )
            : back()->with('status', 'Error adding ad : ' . $e->getMessage());
        return;
    }

    return $request->wantsJson()
        ? new JsonResponse($ad, HTTP_RESPONSE_OK)
        : back()->with('status', 'Ad saved succesully');
}

哪条路是正确的?
谢谢!

nnsrf1az

nnsrf1az1#

onError()回调函数只有在会话中有一个特定的标记errors时才会被调用,因此,在服务器的catch块中,需要刷新用户会话中的错误,并重定向到调用页面:

try {
  // errors throw here
} catch {
   return back()->with('errors', 'Error adding ad');
}

相关问题