laravel 中自定义 api 接口的错误消息

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hjh15827475896/article/details/84801163

当在laravel 中编写 api 接口时,throw new Exception() 返回的错误消息格式不是我们想要的格式

解决办法:

在 App\Exceptions目录下新建一个 ApiException类 继承 Exception 

namespace App\Exceptions;

class ApiException extends \Exception{

    public function __construct($message="")
    {
        parent::__construct($message);
    }
}

 之后,laravel 的所有错误处理都是在 App\Exceptions\Handler.php中处理的

这个类中主要有两个方法 一个是 report   一个是render

report与我的的错误处理无关,我们在这里要改写一个 render方法

下面是render的原始方法

/**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {

        return parent::render($request, $exception);
    }

在render中我们可以判断一下 $exception 是不是我们定义的 ApiException的一个实例,然后做相应的处理

代码如下

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        //如果$exception 是 ApiException的一个实例,则自定义返回的错误信息
        if($exception instanceof ApiException){
            $result = [
                "code"=>422,
                "msg"=>$exception->getMessage(),
                "data"=>""
            ];
            return response()->json($result);
        }
        //如果不是,则使用 父类的处理方法
        return parent::render($request, $exception);
    }

此时,当在写 api接口的时候,如果想抛出一个错误,就可以使用 throw new ApiException("这是一个错误");

数据就会以 json格式返回错误信息

猜你喜欢

转载自blog.csdn.net/hjh15827475896/article/details/84801163