如果面對一個邏輯錯誤錯誤,例如(過期的用戶,無效的ID ),那麼什麼是告訴這個錯誤的父類的方法的最好辦法
既然你想要的父類的方法知道的錯誤,它的接縫,你是不知道,ID
是啥User
在您致電GetUser
方法之前沒有過期。對?
如果您不確定傳遞給函數的參數是否有效,那麼使用異常是不合理的,您應該返回錯誤信息。
您可以返回錯誤信息更多功能方式類似於Scala,Go和Rust語言建議。
創建一個泛型類返回任何錯誤或值
public class Either(of ErrorType, ValueType)
public readonly Success as boolean
public readonly Error as ErrorType
public readonly Value as ValueType
public sub new(Error as ErrorType)
me.Success = False
me.Error = Error
end sub
public sub new(Value as ValueType)
me.Success = True
me.Value = Value
end sub
end class
創建錯誤的枚舉,你的函數可以有
public enum UserError
InvalidUserID
UserExpired
end enum
創建一個函數,用戶ID作爲參數並返回錯誤或用戶
function GetUser(ID as integer) as Either(of UserError, User)
if <business logic to find a user failed> then
return new Either(of UserError, User)(UserError.InvalidUserID)
end if
if <user expired> then
return new Either(of UserError, User)(UserError.UserExpired)
end if
return new Either(of UserError, User)(User)
end function
在了錯誤的調用者(父母)的方法檢查,並應用業務邏輯
dim UserID = 10
dim UserResult = GetUser(10)
if UserResult.Success then
rem apply business logic to UserResult.Value
else
rem apply business logic to UserResult.Error
end if
注:如果您使用改寫例外,你會得到完全同樣的代碼量的代碼。
**嘗試**,** catch **和** throw **,第一個是最好的.. – NetStarter 2013-04-08 07:24:19
請參閱[此問題](http://stackoverflow.com/questions/3926086/handling-已知的錯誤和錯誤的消息-IN-A-方法?RQ = 1)。 – 2013-04-08 07:24:38
我現在可以爲什麼? – 2013-04-08 07:24:48