【发布时间】:2020-03-06 01:41:21
【问题描述】:
我不熟悉 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)
});
【问题讨论】:
-
这能回答你的问题吗? Laravel Redirect Back with() Message
-
我尝试了您提供的答案中的所有解决方案,但没有运气,问题可能与语法无关,而是方法,我可以登录到控制台任何错误代码,如
return response([], 389);,但无法重定向或以json格式回复 -
你能提供你的vue组件的代码吗?
-
当然,只要满足表单请求的规则,组件就可以正常工作
标签: php laravel exception http-status-code-422