iT邦幫忙

2025 iThome 鐵人賽

DAY 28
0

沒想到轉眼就要30天了,先容我將進度快轉到第八章XD
第八章的主題是除錯

Debugging in js

因為 js 本身為 Dynamic Typing language, weakly typed language
像是:

  • 宣告變數的時候不需要強制定義變數的類別(type),變數的類型也可能在執行程式的過程改變
  • 即使變數的型別不符,js 也會自動嘗試轉換變數型別,使操作成功
// 宣告變數時不需要定義 type
let name = 'Mathrew';
name = 123;

let someVal = 3; // number
let someString = 'Glad to see you.' // string

console.log(someString + someVal); // "Glad to see you.3" 會自動將 number 轉換型別為 string

這使 js 很有彈性但也同時導致容易產生錯誤
這時候有幾個方法可以有效去減少錯誤或者追蹤錯誤從哪裡產生

use strict

請使用嚴格模式
用法相當簡單,直接在 code 頂端添加 use strict; 即可

舉例來說
假設不小心忘記在 for loop 建立初始的變數..

let shoppingList = ["notebook", "pen", "eraser"];
function loopSth(arr) {
    // forget to declare variable with let
    for (v of arr) {
        console.log(`I need to buy ${v}.`);
    }
}
loopSth(shoppingList); // js 會幫你建立名為 v 的變數,所以是可以被執行的..

但如果使用了嚴格模式..

"use strict";
let shoppingList = ["notebook", "pen", "eraser"];
function loopSth(arr) {
    // forget to declare variable with let
    for (v of arr) {
        console.log(`I need to buy ${v}.`);
    }
}
loopSth(shoppingList);  // Uncaught ReferenceError: v is not defined

異常狀態管理

use simple returns for simple checks, and use structured objects for complex or unavoidable failures

return null, undefined 等 falsy value

當 function 執行時僅需對 parameter 做簡單檢查,或錯誤顯而易見的情況
可直接回傳 falsy value

舉例來說 promptName 僅對 name 做檢查,不符合型態則直接回傳錯誤值

function promptName(name){
    if (typeof name!== string || !name){
        return false;
    }else{
        console.log(`user name is :${name}`)
    }
}

return 帶有更多訊息的 object

當 function 執行時需明確區分成功與失敗的情況,或可能有多種導致程式有異常的情況
則需要回傳帶有更詳細錯誤訊息的 object,有助於知道到底是程式是哪個階段失敗而產生異常

舉例來說
像是 fetch data from api

function fetchUserData(id) {
    if (id <= 0) {
        // Failure 1: Invalid Parameter
        return { error: 'Invalid ID: Must be positive.' }; 
    }
    // ... network code ...
    if (response.status === 404) {
        // Failure 2: Resource Not Found
        return { error: 'User not found.' }; 
    }
    // Success
    return { user: data }; 
}

上一篇
Chapter 7 實作專案-6(路徑搜尋)-day27
系列文
溫故而知新:Eloquent Javascript 閱讀筆記28
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言