1. 程式人生 > 遊戲 >劇情探索遊戲《Hindsight》主機版將於12月6日發售

劇情探索遊戲《Hindsight》主機版將於12月6日發售

1.新建異常類 php artisan make:exception ApiException

<?php

namespace App\Exceptions;

use Exception;
use Throwable;

class ApiException extends Exception
{
    public function __construct($message = "", $code = 400, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

    public function render()
    {
        return response()->json([
            'msg' => $this->message,
            'code' => $this->code,
        ], $this->code);
    }
}

2.方法中使用異常類

引入異常類
use App\Exceptions\ApiException;


方法中丟擲異常
throw new ApiException('該商品不存在');

3.如果有使用Dingo,Dinggo會接管laravel的異常,render()方法不被執行,需要在服務提供者中遮蔽部分資訊,找到app\Providers\AppServiceProvider.php中的boot方法,新增遮蔽程式碼

public function boot()
{
    Schema::defaultStringLength(200);

    //有使用dinggo的話,新增如下程式碼遮蔽部分不需要顯示內容
    app('api.exception')->register(function (\Exception $exception) {
        $request = Request::capture();
        return app('App\Exceptions\Handler')->render($request, $exception);
    });
}

4.新建的異常會被寫進laravel的日誌檔案,不需要的可以在異常基類 app\Exceptions\Handler.php 中新增排除

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * 新增不需要寫進laravel日誌的異常類
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        ApiException::class,
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }
}

可以手動寫入

Log::error($this->message);