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

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

Laravel6で確認。


API時のエラー処理を追加

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

\app\Exceptions\Handler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?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 件のコメント :

コメントを投稿