博文記錄
PHP 2020-01-26 00:16:11 2256 0

Laravel 自定义错误消息

在 Laravel 验证请求时出现错误,默认会返回如下的错误:

可以看到 JSO 结构中的 message 为The given data was invalid.而并非是我们具体自定义的错误,这在用户端显得非常不友好。

在谷歌找了半天都是教你如何通过语言包的形式修改为本地化的语言,实质上和我们的需求有些出入,并不能获取的具体的错误内容。

最终,在 laravel 的 issue 中找到一则帖子:https://github.com/laravel/framework/issues/21059

其实我很同意这个帖子主题,和我遇到的情况一致,但被关闭了。

文中有一些其他人给出的解决思路,如下:

修改文件:app/Exceptions/Handler.php

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Exception
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof ValidationException && $request->expectsJson())
return response()->json(['message' => $exception->validator->errors()->first(), 'errors' => $exception->validator->getMessageBag()], 422);
        return parent::render($request, $exception);
    }

通过修改 render 方法得以实现对请求异常时返回的 json 内容。

如果想更改为其他的 json 结构,也可以在此进行修改。

其实如果只是想更改 JSON 结构可以通过重写 invalidJson 实现,依然在这个文件里:


    /**
     * Convert a validation exception into a JSON response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Validation\ValidationException  $exception
     * @return \Illuminate\Http\JsonResponse
     */
    protected function invalidJson($request, ValidationException $exception)
    {
        return response(eeData($exception->getMessage(), $exception->status));
    }

其中的 eeData 为我自己自定义的 JSON 结构函数。

索引目录
media iamge
StudioEIM - 冒险者讲习所
0:00