Laravel Api不从Request类发送必需的错误json消息

问题描述 投票:0回答:1

请求类别

class LoginRequest extends FormRequest
{
    public function wantsJson() {
        return true;
    }   

    public function authorize() {
        return true;
    }

    public function rules() {
        $validators = [
            'email'    =>  'required',
            'password' =>  'required'
        ];
        return $validators;
    }

    public function failedValidation(\Illuminate\Contracts\Validation\Validator $validator) {
        if($validator->fails()) {
            //print_r($validator->errors());
            //die();

        }
        return parent::failedValidation($validator);
    }
}

我有一个用Laravel编写的api。我正在尝试通过Postman扩展程序测试验证。当我提交一些电子邮件和密码值时,它可以工作。我收到有关凭据是否存在的消息。

如果我不提交值,那么就不会返回json messagebag。

我可以确认MessageBag中存在验证错误消息。这是屏幕截图。如果屏幕截图不清楚,请点击查看。

另一个奇怪的是,返回的状态码是200

请让我知道是否需要更多信息

enter image description here

laravel laravel-5.7 laravel-5.8
1个回答
1
投票

在我的情况下,我像这样设置Laravel API。

在我的App\Exceptions\Handler

public function render($request, Exception $exception)
    {
        // return parent::render($request, $exception);

        $rendered = parent::render($request, $exception);

        if ($exception instanceof ValidationException) {
            $json = [
                'error' => $exception->validator->errors(),
                'status_code' => $rendered->getStatusCode()
            ];
        } elseif ($exception instanceof AuthorizationException) {
            $json = [
                'error' => 'You are not allowed to do this action.',
                'status_code' => 403
            ];
        }
        else {
            // Default to vague error to avoid revealing sensitive information
            $json = [
                'error' => (app()->environment() !== 'production')
                    ? $exception->getMessage()
                    : 'An error has occurred.',
                'status_code' => $exception->getCode()
            ];
        }

        return response()->json($json, $rendered->getStatusCode());
    }

也将此导入到顶部

use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;

它有助于将错误格式化为JSON格式。

我的LoginRequest看起来像这样(简单)

class LoginRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'email' => 'required|email',
            'password' => 'required'
        ];
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.