iT邦幫忙

2021 iThome 鐵人賽

DAY 9
2
Software Development

全端開發包括測試自己一條龍!系列 第 9

Day 9 - Laravel 8.0的Error Handling

  • 分享至 

  • xImage
  •  

不管是預期或非預期,程式往往會發生一些錯誤,我們不希望使用者Call API或瀏覽網頁的時候發生錯誤直接跳出像下面一樣的錯誤訊息

如果太過詳細的錯誤訊息可能會造成資安的危機,所以我們需要先把.envAPP_DEBUG的值改為False,如此一來我們看到的錯誤訊息會變成這樣

接下來我們需要把這些錯誤訊息做處理,修改app\Exceptions\Handler

  • use Laravel本身就擁有的Exception
  • $this->renderable()內部撰寫閉包傳入Exception和Request
  • 寫一個新的handleException function專門做Response的處理,當中會從傳入的exception判斷是屬於哪種錯誤,判斷完後傳回自訂的Response message
<?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

  1. 傳入未知的route

  2. 預期的route,但是傳入未定義的Method

  3. 預期的route和method,但身分驗證錯誤


上一篇
Day 8 - Laravel Request validation
下一篇
Day 10 - Laravel使用Phpunit做單元測試
系列文
全端開發包括測試自己一條龍!10
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
柴柴
iT邦新手 5 級 ‧ 2022-04-09 20:32:58

您好,
我想請教一個問題,就是關於驗證的錯誤訊息
也應該設計在這個Handler.php裡嗎
還是要另外設計一個class放response()->json()呢?

例如:
客戶端把number打成string,
權限解析失敗,

我要留言

立即登入留言