我的解决方案使用 "flugger/laravel-responder": "^3.1" 包解决了 Laravel 版本 8。
-
安装flugger/laravel-responder package
-
安装后。发布包。
$ php artisan vendor:publish --provider="Flugg\Responder\ResponderServiceProvider"
- 您可以查看
app\config\responder.php 文件。
...
'serializers' => [
'success' => Flugg\Responder\Serializers\SuccessSerializer::class,
'error' => \Flugg\Responder\Serializers\ErrorSerializer::class,
],
...
此配置是格式类的路径。您可以制作自己的自定义甲酸盐类。只需创建并覆盖其中的函数即可。
- 创建您自己的异常处理程序。
php artisan make:exception NotLoginException
<?php
namespace App\Exceptions;
use Flugg\Responder\Exceptions\Http\HttpException;
class NotLoginException extends HttpException
{
protected $status = 401;
/**
* The error code.
*
* @var string|null
*/
protected $errorCode = '401';
/**
* The error message.
*
* @var string|null
*/
protected $message = 'User not logged in.';
}
- 在
app\Exceptions\Handler.php。重写函数render:
// don't forget to use these class;
...
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Flugg\Responder\Exceptions\ConvertsExceptions;
use Laravel\Passport\Exceptions\OAuthServerException;
class Handler extends ExceptionHandler
...
public function render($request, Throwable $e)
{
$this->convertDefaultException($e);
if($e instanceof OAuthServerException) {
throw new PermissionDenyException();
}
if (
$e instanceof NotLoginException ) {
// you don't have always to do this. you can render your own Excption here.
return $this->renderResponse($e);
}
return parent::render($request, $e);
}
-
注意OAuthServerException 只是passport 异常之一。我不确定passport 是否还有其他例外情况。
检查异常类型。只需在渲染函数中使用get_class($e);。然后就可以看到异常的类类型了。所以,你可以处理它。
-
你可以看到结果
{
"status": 401,
"success": false,
"error": {
"code": "401",
"message": "User not logged in."
}
}