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!

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.