laravel api统一返回错误格式怎么做

以下的是表单验证的返回格式,很棒也很舒服

{
    "message": "The given data was invalid.",
    "errors": {
        "captcha_code": [
            "请填写图片验证码"
        ]
    }
}

但是有些验证在表单验证做不了,如abort(403, ‘图片验证码已失效’,[]);

{
    "message": "图片验证码已失效"
}

如何统一为表单验证的返回格式?先行谢过大佬。

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

Plan A:用自定义异常吧,别用 abort() 了。

Plan B:在app/Exceptions/Handler.php中,重写render()方法

<?php

namespace App\Exceptions;

class Handler extends ExceptionHandler
{
    public function render($request, \Throwable $e)
    {
        return response([
            'message' => $e->getMessage(),
            'errors' => $e->getMessage(),
        ]);
    }
}
4年前 评论
ShamGod 3年前
LiamHao (作者) 3年前
讨论数量: 4

Plan A:用自定义异常吧,别用 abort() 了。

Plan B:在app/Exceptions/Handler.php中,重写render()方法

<?php

namespace App\Exceptions;

class Handler extends ExceptionHandler
{
    public function render($request, \Throwable $e)
    {
        return response([
            'message' => $e->getMessage(),
            'errors' => $e->getMessage(),
        ]);
    }
}
4年前 评论
ShamGod 3年前
LiamHao (作者) 3年前

博客:一种 Laravel 异常上下文解决方案 看这个里面有我的回复,抄作业就行了,具体逻辑自己安排

4年前 评论

将表单的第一个错误放到 message 里

// app/Exceptions/Handler.php
...
protected function invalidJson($request, ValidationException $exception)
    {
        $errors = $exception->errors();
        $firstError = \reset($errors);

        return response()->json([
            'message' => $firstError[0] ?? '参数错误',
            'errors' => $errors,
        ], $exception->status);
    }
...
3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!