本頁重點提要

  • 01.先驗證輸入,再 try-catch 守外部邊界。
  • 02.回應分層:使用者訊息 vs 工程診斷資訊。
  • 03.自訂例外只用在需要表達領域語意的場景。

實戰模板:驗證 + 防護 + log + 回應

下面是一個工程上常見的模板:輸入驗證 → try-catch 守外部邊界 → log 診斷 → 回傳使用者訊息

public (bool ok, string message) CreateOrder(string userId, string amountText)
{
    // 1) Validation
    if (string.IsNullOrWhiteSpace(userId))
        return (false, "使用者資訊不完整");

    if (!decimal.TryParse(amountText, out var amount) || amount <= 0)
        return (false, "金額格式不正確");

    // 2) Boundary protection
    try
    {
        // TODO: call DB / external services
        // _repo.Insert(...)
        return (true, "建立成功");
    }
    catch (TimeoutException ex)
    {
        // TODO: logger.Warn(ex, ...)
        return (false, "系統繁忙,請稍後再試");
    }
    catch (Exception ex)
    {
        // TODO: logger.Error(ex, ...)
        return (false, "系統發生錯誤,請聯絡客服");
    }
}

工程規範 05:自訂例外(Custom Exception)只用在「你真的要表達領域語意」時

例如:PaymentDeclinedException / InventoryInsufficientException。不要為了好看而把所有錯誤都包一層。

Implementation Reference
public (bool ok, string message) CreateOrder(...) { /* template */ }
Switch Page