不管是預期或非預期,程式往往會發生一些錯誤,我們不希望使用者Call API或瀏覽網頁的時候發生錯誤直接跳出像下面一樣的錯誤訊息
如果太過詳細的錯誤訊息可能會造成資安的危機,所以我們需要先把.env中APP_DEBUG的值改為False,如此一來我們看到的錯誤訊息會變成這樣
接下來我們需要把這些錯誤訊息做處理,修改app\Exceptions\Handler
$this->renderable()內部撰寫閉包傳入Exception和Request<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Exception;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
class Handler extends ExceptionHandler
{
    /**
     * 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 = [
        'current_password',
        'password',
        'password_confirmation',
    ];
    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->renderable(function(Exception $e, $request) {
            return $this->handleException($request, $e);
        });
    }
    /**
     * Handle response from exception.
     *
     * @param Request $request
     * @param \Exception $exception
     * @return JsonResponse|null
     */
    private function handleException($request, Exception $exception)
    {
        switch (true) {
            case $exception instanceof NotFoundHttpException:
                return response()->json([
                    'message' => 'Http not found.'
                ], 404);
            case $exception instanceof MethodNotAllowedHttpException:
                return response()->json([
                    'message' => 'Method not allowed.'
                ], 405);
            case $exception instanceof UnauthorizedHttpException:
                return response()->json([
                    'message' => 'Unauthorized.'
                ], 401);
        }
        return null;
    }
}
改完後,再來試試我們的API
傳入未知的route
預期的route,但是傳入未定義的Method
預期的route和method,但身分驗證錯誤
您好,
我想請教一個問題,就是關於驗證的錯誤訊息
也應該設計在這個Handler.php裡嗎
還是要另外設計一個class放response()->json()呢?
例如:
客戶端把number打成string,
權限解析失敗,