问题描述
如果从数据库获取数据时出现错误或任何其他问题,我将发送这样的错误消息:
I am sending error messages like this in case of errors in getting data from DB or any other issue:
return response()->json(['status' => 'Failed' ,'state'=>'100' , 'message'=>'You have not registered yet.' ], 401);
这为我提供了一个定义了所有内容的JSON,因此无论出现什么问题,我都可以轻松显示该消息.
This gives me a JSON which has everything defined so I easily show the message whatever the problem is.
但是如果在验证时出错,我似乎没有权力更改错误响应JSON的格式.
But in case of error in case of validation, I don't seem to have the power to change the format of the error response JSON.
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
我想自定义错误格式为上面给出的格式,这样我就不必更改错误显示机制.
I want to customize the error format as the one given above so that I don't have to change my error showing mechanism.
推荐答案
您可以手动创建验证器,并在失败时添加自定义响应,如下所示:
You can manually create a validator and add your custom response if it fails, like this:
$validator = Validator::make($request->all(), [
'email' => 'required',
'password' => 'required'
]);
if ($validator->fails()) {
return response()->json(['status' => 'Failed' ,'state'=>'100' , 'message'=> $validator->errors()->first() ], 401);
}
这篇关于如何在Lumen中自定义错误的JSON格式(Laravel)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!