How can I return only a string from an error?
I would like to return only: "not found" or "can't delete".
Right now, the returned error is: The operation couldn't be completed. (Invoice.BackEnd Error 2.)
code that makes the request:
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
}
}
part of the code inside the delete button:
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)
})
} )
Start by defining your completion handler to return BackendError instead of Error. That will make things a little easier.
Then you need to use a switch on the error to get the reason value:
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With