处理laravel 引入 dingo/api 422 数据格式前端无法使用

在 AppServiceProvider 中:

 

use Dingo\Api\Exception\ValidationHttpException;
use Dingo\Api\Facade\API;
public function boot()
{
\Carbon\Carbon::setLocale('zh');  //carbon本地化
Schema::defaultStringLength(191);//数据库兼容问题
//
}
public function register()
{
//处理模型为查找到
API::error(function (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) {
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('未查询到数据');
});
//处理验证数据类型
API::error(function (ValidationHttpException $exception) {
foreach ($exception->getErrors()->toArray() as $key => $value){
abort(422,$value[0]);
return;
}
});
}
 
 
 
在Hander.php中:
public function render($request, Exception $e)
{
if ($e instanceof Exception) {
$result = [
"msg" => $e->getMessage(),
"data" => '',
"type" => 'Exception',
"code" => 201,
"trace" => $e->getTrace(),
];
return response()->json($result, 202);
}
return parent::render($request, $e);
}
posted @ 2018-10-12 21:05  花泪哲  阅读(824)  评论(0)    收藏  举报