# Error Message Swift 4.2

**URL:** <https://forums.swift.org/t/error-message-swift-4-2/60472>\
**Category:** Using Swift\
**Created:** [September 23, 2022, 5:20pm UTC](https://forums.swift.org/t/error-message-swift-4-2/60472 "2022-09-23T17:20:18Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![faustus-gomes](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/faustus-gomes/32/26956_2.png) [@faustus-gomes](https://forums.swift.org/u/faustus-gomes)\
**Post date:** [September 23, 2022, 5:20pm UTC](https://forums.swift.org/t/error-message-swift-4-2/60472/1 "2022-09-23T17:20:18Z")

</div>

Hi guys.  
Help me!  
My API is perfect.

My code Swift is stranger error, but it writes perfectly to the database via API.

Code:  
@IBAction func register\_click(\_ sender: Any) {  
//if not text

```
    if usernameTxt.text!.isEmpty || passwordTxt.text!.isEmpty || emailTxt.text!.isEmpty || firstnameTxt.text!.isEmpty || lastnameTxt.text!.isEmpty {
        usernameTxt.attributedPlaceholder = NSAttributedString(string: "username", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])
        
        passwordTxt.attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])
        
        emailTxt.attributedPlaceholder = NSAttributedString(string: "email", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])
        
        firstnameTxt.attributedPlaceholder = NSAttributedString(string: "name", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])
        
        lastnameTxt.attributedPlaceholder = NSAttributedString(string: "surname", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])
        
    } else {
        // if entered - create new user mysql
        // remove keyboard
        self.view.endEditing(true)
        
        // url to php file
        let url = URL(string: "http://localhost/Twiter/register.php")
        // request to php file
        var request = URLRequest(url: url!)
        // method to pass data to this file (e.g. via POST)
        request.httpMethod = "POST"
        
        //request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        
        //request.addValue("application/json", forHTTPHeaderField: "Accept")
        //request.setValue( "application/json", forHTTPHeaderField: "Authorization")
        //request.setValue("application/json; application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        
        // body to be appended to url
        let body = "username=\(usernameTxt.text!.lowercased())&password=\(passwordTxt.text!)&email=\(emailTxt.text!)&fullname=\(firstnameTxt.text!)%20\(lastnameTxt.text!)"
        
        
        
        request.httpBody = body.data(using: .utf8) //allowLossyConversion: true
        
        // proceed request URLSession.shared.dataTask(with: request) { data, response, error in
        URLSession.shared.dataTask(with: request) { data, response, error in
            if error == nil {
        //=================================================================================
                guard let data = data else {return}
                
                // get main queue in code process to communicate back to UI
                DispatchQueue.main.async(execute: {
                 do {
                 // get json result
                 let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary //.allowFragments
                 
                 // assign json to new var parseJSON in guard/secured way
                    guard let parseJSON = json else {
                 print("Error parsing parsing")
                 return
                 }
                 
        
                 
                 // get id from parseJSON dictionary
                 let id = parseJSON["id"]
                 
                 // successfully registered
                 if id != nil {
                 //print(parseJSON)
                 /*DispatchQueue.main.async(execute: {
                 let message = parseJSON["message"] as! String
                 appDelegate.infoView(message: message, color: colorLightGreen)
                 print("Sucesso!")
                 })*/
                 // save user information we received from our host
                 UserDefaults.standard.set(parseJSON, forKey: "parseJSON")
                 user = UserDefaults.standard.value(forKey: "parseJSON") as? NSDictionary
                 
                 // go to tabbar / home page
                 DispatchQueue.main.async(execute: {
                 //appDelegate.login()
                 print("Sucesso")
                 })
                 
                 
                 // error
                 } else {
                 //get main queue to comunicate back to user
                 DispatchQueue.main.async(execute: {
                 let message = parseJSON["message"] as! String
                 //appDelegate.errorView(message: message)
                 appDelegate.infoView(message: message, color: colorSmoothRed)
                 print("Erro sem sucesso\(parseJSON)")
                 })
                 }
                 
                 }
                 
                 catch {
                 DispatchQueue.main.async(execute: {
                 let message = "Erro de Comunicação\(error)"
                 appDelegate.infoView(message: message, color: colorSmoothRed)
                 })
                 }
                 
                 
                 })
                 // if unable to proceed request
                 } else {
                 // get main queue to comunicate back to user
                 DispatchQueue.main.async(execute: {
                 let message = error!.localizedDescription
                 appDelegate.infoView(message: message, color: colorSmoothRed)
                 print("sem comunicação!")
                 })
                
                

        //=====================================================================================
           // } else {
           // print("Sem sucesso!")
            }
            
        // launch prepared session
        } .resume()
      
    }

```

The message is: "Erro ComunicaçãoError  
Domain = NSCocoaErrorDomain code=3840" JSON ....

---

<div class="post-metadata">

**Author:** ![mhelenurm](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mhelenurm/32/20864_2.png) [@mhelenurm](https://forums.swift.org/u/mhelenurm)\
**Post date:** [September 24, 2022, 7:12pm UTC](https://forums.swift.org/t/error-message-swift-4-2/60472/2 "2022-09-24T19:12:33Z")

</div>

I bet that `try JSONSerialization` when the API returns data is throwing an error (JSON parse error, like what was printed). If an error is thrown, it gets handled in the `catch` block, not at the `guard`; if you change your `try JSON...` to a `try? JSONSerialization.jsonObject(...)` that will make it fail at the `guard` instead (giving you "Error parsing parsing" instead).

These two ways of expressing a `try` give equivalent results (except one lets you see the actual error):

```swift
func pattern1() {
    guard let result = try? throwingMethod() else {
        print("I will print here if there's an error. We don't have access to the actual error, so I can't print it")
    }

    print("We have a value: \(result)")
}

func pattern2() {
    do {
        let result = try throwingMethod()
        print("We have a value: \(result)")
    } catch {
        print("I will print here if there's an error. Here's the error: \(error)")
    }
}

```

The tradeoff in this pattern: "can I get the error's value" vs "can I use one fewer indentation level once I'm holding the result of the throwing method". A third pattern: mark `pattern3` as throwing, and pass the error to be someone else's responsibility... You can immediately access the value without a level of indentation being created, and no `guard` or `do` block at all!
