Laravel自定義JSON錯誤消息 The given data was invalid.


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結構函數。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM