如何只返回错误中的字符串?
我只想回复:"未找到"或者"无法删除"。
目前,返回的错误是:操作无法完成。 (Invoice.BackEnd错误2。)
发出请求的代码:
enum BackendError: Error {
case urlError(reason: String)
case objectSerialization(reason: String)
case objectDeletion(reason: String)
}
struct Meta: Codable {
let sucess: String
let message: String!
}
if let httpResponse = response as? HTTPURLResponse{
if httpResponse.statusCode == 200{
print("deleted")
let response = Meta(sucess: "yes", message: "deleted")
completionHandler(response, nil)
return
}
else if (httpResponse.statusCode == 404) {
let error = BackendError.objectDeletion(reason: "not found")
completionHandler(nil, error)
return
}
else {
let error = BackendError.objectDeletion(reason: "can't delete")
completionHandler(nil, error)
return
}
}
删除按钮内的部分代码:
makeDelete(httpMethod: "DELETE",endpoint: endPoint,
parameters: [:],
completionHandler: { (container : Meta?, error : Error?) in
if let error = error {
print("error on /delete")
self.showAlert(title: "Error", message: error.localizedDescription)
return
}
self.wasDeleted = true
//change message and use the custom func like on error.
let alert = UIAlertController(title: "Success!", message: "Client Deleted.", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(_)in
self.performSegue(withIdentifier: "unwindToClients", sender: self)
})
alert.addAction(OKAction)
DispatchQueue.main.async(execute: {
self.present(alert, animated: true, completion: nil)
})
} )
答案 0 :(得分:2)
首先定义完成处理程序以返回BackendError
而不是Error
。这将使事情变得更容易。
然后您需要在错误上使用switch
来获取reason
值:
makeDelete(httpMethod: "DELETE",endpoint: endPoint,
parameters: [:],
completionHandler: { (container : Meta?, error : BackendError?) in
if let error = error {
print("error on /delete")
let message: String
switch error {
case let .objectDeletion(reason):
message = reason
default:
message = error.localizeDescription
}
self.showAlert(title: "Error", message: message)
return
}