BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: How do I capture an exception/stack trace?

Forums > 100 Days of SwiftUI

I have an if let and I'd like to display the error details in an alert when it fails but I'm not sure how to do that.

if let decodedUsers = try? JSONDecoder().decode([User].self, from: data) {
   users = decodedUsers
} else {
   showingError = true
   errorMessage = "Failed to decode data"
}

I'd like to replace the string literal "Failed to decode data" with an exception message or a stack trace. In C#/.NET you would use try/catch like this:

try {
   doSomething();
} catch (Exception ex) {
   errorMessage = ex.message;
}

The exception object is fed into the catch block as a parameter. How can I achieve the same thing or something similiar in swift?

   

Write a function with your code which can fail and mark the function as throws. You should be able to catch errors in your function which you don't want to delegate to the caller and throw only those errors you want to show a message,

   

Replace this:

if let decodedUsers = try? JSONDecoder().decode([User].self, from: data) {
   users = decodedUsers
} else {
   showingError = true
   errorMessage = "Failed to decode data"
}

with something like this:

do {
    users = try JSONDecoder().decode([User].self, from: data)
} catch {
    showingError = true
    errorMessage = error.localizedDescription //you can also try "\(error)"
}

   

Do I have to declare error?

   

Do I have to declare error?

Nope, the compiler handles that for you.

See Handling Errors Using Do-Catch in the language guide for more details.

   

Thanks @roosterboy!

   

Hacking with Swift is sponsored by Guardsquare

SPONSORED AppSweep by Guardsquare helps developers automate the mobile app security testing process with fast, free scans. By using AppSweep’s actionable recommendations, developers can improve the security posture of their apps in accordance with security standards like OWASP.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.