下面是一個工程上常見的模板:輸入驗證 → 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。不要為了好看而把所有錯誤都包一層。