salmanzafar / laravel-api-exceptions-handler
一个使处理和自定义API异常及响应变得容易的Laravel包
v1.0.4
2021-04-27 19:50 UTC
Requires
- php: >=7.3.0
Requires (Dev)
- laravel/framework: >=8.0
README
一个使处理和自定义API异常及响应变得容易的Laravel包,并且支持模型uuid
目录
安装
composer require salmanzafar/laravel-api-exceptions-handler --dev
配置(可选)
发布服务提供者
php artisan vendor:publish --provider="Salman\ApiExceptionHandler\ApiExceptionHandlerServiceProvider::class"
启用包(可选)
此包实现了Laravel自动发现功能。安装后,自动为laravel >= 5.5添加了包提供者和外观。
API异常
有许多情况,您希望返回一个自定义响应到API而不是默认响应
例如,您有一个获取用户的API,您想返回一个自定义响应而不是Laravel默认响应
public function getUser(User $user) { return $user; }
在上面的情况下,默认情况下,如果用户未找到,Laravel将抛出404异常。现在让我们看看我们如何自定义它
转到 app\Exceptions\Handler.php
并复制粘贴以下部分
namespace App\Exceptions; use Exception; use App\Exceptions\ExceptionTrait; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class Handler extends ExceptionHandler { use ExceptionTrait; /** * A list of the exception types that are not reported. * * @var array */ protected $dontReport = [ // ]; /** * A list of the inputs that are never flashed for validation exceptions. * * @var array */ protected $dontFlash = [ 'password', 'password_confirmation', ]; /** * Report or log an exception. * * @param \Exception $exception * @return void */ public function report(Exception $exception) { parent::report($exception); } /** * 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) { if ($request->expectsJson()) { return $this->ApiExceptions($request,$exception); } return parent::render($request, $exception); } }
ExceptionTrait
包含所有的异常处理- 在
render函数
中,我们添加了条件检查,然后返回了apiExceptions
现在它将返回自定义的JSON响应而不是默认的Laravel响应(见下文)
{ "error": "Model Not found" }
自定义API响应
有很多情况,您希望自定义Laravel默认的验证/表单请求响应,在这种情况下,这将帮助您自定义响应
让我们看看Laravel的默认验证响应
{ "message": "The given data is invalid", "errors": { "name": ['name is require'] } }
现在让我们通过创建一个表单请求来修改它,例如 CarRequest.php
<?php namespace App\Http\Requests; use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Salman\ApiExceptionHandler\Concerns\MyValidationException; class CarRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ // ]; } protected function failedValidation(Validator $validator) { throw new MyValidationException($validator); } }
现在API响应将是
{ "error": "The name field is required" }
我们所做的就是在我们请求中添加了 failedValidation
并抛出了我们的异常
您可以根据需要轻松修改上述错误,只需发布此文件 MyValidationException
模型UUID
有许多情况,我们想在模型中将 uuid
作为 主键
使用,现在这也更容易,您可以在瞬间将 uuid
作为 pk
使用
namespace App; use \Salman\ApiExceptionHandler\Concerns\UsesUuid; use Illuminate\Database\Eloquent\Model; class Car extends Model { use UsesUuid; }
只需在您的模型中使用 UsesUuid
,现在您在模型中就有 uuid
作为 pk
。别忘了在迁移中做出更改
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCarsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('cars', function (Blueprint $table) { $table->uuid('id')->primary(); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
发布文件
以下命令将发布 App\Concerns
文件夹内所有相关文件
php artisan publish:traits