Laravel API接続時のエラー出力方法

LaravelでAPI接続時にエラーの場合の出力をまとめ。

Laravel6で確認。


API時のエラー処理を追加

\app\Exceptions\Handler.phpのファイルを編集してrenderのメソッドを編集します。

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Log;

class Handler extends ExceptionHandler
{

# ~~~~~~~~~~~~~~~

    /**
     * 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)
    {
        // API判定
        if ($request->is('ajax/*') || $request->is('api/*') || $request->ajax()) {

            // Exceptionの種類によって分ける
            if($exception instanceof ValidationException){
                $response = [
                    'data' => $this,
                    'status' => 'NG',
                    'summary' => 'Failed validation.',
                    'errors' => $exception->errors(),
                ];
                return response()->json( $response, 422 );
            }

            $response = [
                'data' => [],
                'status' => 'NG',
                'summary' => 'Server Error',
                'errors' => ['error' => 'Server Error'],
            ];

            $is_debug = config('app.debug');
            if($is_debug){
                // デバック時は詳細なエラーメッセージ
                $response['errors'] =['error' => $exception->getMessage()];
            }
            
            // ログ出力
            Log::error($exception->getMessage());
            return response()->json($response, 500);
        }
        Log::error($exception->getMessage());
        return parent::render($request, $exception);
    }
}

Laravel Model バリデーション実装 と組み合わせて使用することが可能です。

0 件のコメント :

コメントを投稿