NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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 Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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

Reply to this topic…

You need to create an account or log in to reply.

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.