Swift错误处理:身份验证系统

时间:2020-01-31 17:58:07

标签: swift

我无法在Swift上显示自定义错误消息。

该方案是使用字典数据进行基本的用户身份验证,使用字典数据对输入进行验证,如果用户名和密码匹配,则返回true,否则将显示错误消息“ 无效的凭证”,并带有{{ 1}}出现(参数消息AuthenticationError枚举)

这是我到目前为止提出的代码:

CustomErrors

上面的代码非常适合所有积极的测试案例,例如:

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

1 个答案:

答案 0 :(得分:1)

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
}

现在,如果CustomErrorsuserpass中存储的那些不匹配,则该函数将引发authDict Dictionary错误。