首页 > 解决方案 > 收到 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)
                        });

标签: phplaravelexceptionhttp-status-code-422

解决方案


您可能想要更改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 状态代码。


推荐阅读