UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?

2      

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,

2      

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)"
}

2      

Do I have to declare error?

2      

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.

2      

Thanks @roosterboy!

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.