在最近的一个开发项目中,使用了第三方Api库Dingo/Api。Dingo是一个非常强大的API库,但是在开发的过程中,需要自定义response字段。刚开始使用Ding/Api时,返回如下:{"message":"422UnprocessableEntity","errors":{"mobile":["手机号码格式不正确"]},"status_code":422}这是Dingo在输入字段校验错误时返回的结果。这看起来不错。因为这里的status_code比较规范。对于PHP来说,直接在json_decode之后就没什么难的了。但相反,Android和IOS使用强类型语言。特别是在Java中,需要创建每个Json对象,然后序列化。因此,这种返回结果不统一的解决方案是不可接受的:我们需要将所有的异常信息收集到一个地方,并在AppServiceProvider的boot()方法中添加//将所有的Exceptions交给App\Exceptions\Handler来处理处理app('api.exception')->register(function(Exception$exception){$request=Illuminate\Http\Request::capture();returnapp('App\Exceptions\Handler')->render($请求,$异常);});然后在App\Exceptions\Handler.php中的render()方法中:$class=get_class($exception);switch($class){case'Dingo\Api\Exception\ValidationHttpException':if($request->expectsJson())返回$this->errorRespond($exception->getErrors()->first(),$exception->getStatusCode());休息;默认值:if($request->expectsJson())return$this->errorRespond('Thesystemisatrest',500000);break;}再次访问界面:{"response_status_code":422,"response_message":"请填写手机号","data":[]}
