簡體   English   中英

Swift 錯誤處理:身份驗證系統

[英]Swift Error Handling: Authentication System

我在 Swift 上顯示自定義錯誤消息時遇到問題。

該場景是使用字典數據進行基本用戶身份驗證,輸入的輸入使用字典數據進行驗證,如果用戶名和密碼匹配,則返回 true,否則會出現錯誤消息“無效憑據”和AuthenticationError (參數消息CustomErrors enum)

這是我到目前為止想出的代碼:

import Foundation

//Editable code starts here


let authDict:Dictionary = ["admin":"admin123","user":"someone123","guest":"guest999","you":"yourpass","me":"mypass190"]

//create CustomErrors enum
public enum CustomErrors: Error {
    case AuthenticationError(message:String)
    //case invalidCredentials
}

extension CustomErrors: LocalizedError {
    public var errorDescription: String? {
        switch self{
            //case .invalidCredentials:
            //   return NSLocalizedString("Invalid Credentials", comment: "Invalid Credentials")
        //return "Invalid Credentials"
        case .AuthenticationError(message:let message):
            print(message)
            return "Invalid Credentials"
        }
    }
}
// create authenticate(userName:user,pass:pass) with return type Boolean
func authenticate(user:String,pass:String) -> Bool{
    print(user)
    print(pass)
    for(u,p) in authDict {
        if((u == user) && (p == pass)) {
            return true
        }
    }
    print("Invalid Credentials")
    return false
}
//Editable code ends here
//Uneditable code starts here
let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

guard let user = readLine() else { fatalError("Bad input") }

guard let pass = readLine() else { fatalError("Bad input") }

do{
    let result = try authenticate(user:user,pass:pass)
    fileHandle.write((result ? "1" : "0").data(using: .utf8)!)
}catch CustomErrors.AuthenticationError(let message){
    fileHandle.write(message.data(using: .utf8)!)
}
//Uneditable code ends here

上面的代碼適用於所有正面測試用例,例如:


 1. "admin":"admin123"
 2. "user":"someone123"
 3. "guest":"guest999"
 4. "you":"yourpass"
 5. "me":"mypass190"

以上所有輸出為1 ,但對於負面測試用例,我應該將Invalid Credentials打印為輸出,而不是我得到0

我不確定CustomErrors枚舉中缺少什么,但它不起作用。

如何修復我的可編輯代碼以使用以下不可編輯代碼,我應該添加/刪除什么來實現最終結果:

do{
    let result = try authenticate(user:user,pass:pass)
    fileHandle.write((result ? "1" : "0").data(using: .utf8)!)
}catch CustomErrors.AuthenticationError(let message){
    fileHandle.write(message.data(using: .utf8)!)
}

修改authenticate函數為:

func authenticate(user:String,pass:String) throws -> Bool{
    print(user)
    print(pass)
    guard authDict[user] == pass else {
        throw CustomErrors.AuthenticationError(message: "Invalid Credentials")
    }
    return true
}

現在,如果userpass與存儲在authDict Dictionary中的不匹配,該函數會拋出CustomErrors錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM