Skip to content

Add a way to react to errors #11

Closed

Description

@milanvarady

In many cases, I need to catch the error in a button to show an alert or update some state. It's tedious to always try and catch, what if we could do this:

AsyncButton {
    try await longOperation()
} label: {
    Label("Long Operation", systemImage: "clock")
} error: { error in
    // Do somethig with error
}

Activity

  1. Dean151 commented on Dec 31, 2024

    @Dean151
    Owner

    Hi @milanvarady!
    Would a modifier work?

    AsyncButton {
        try await longOperation()
    } label: {
        Label("Long Operation", systemImage: "clock")
    }
    .onError { error in
        // Do something with error
    }
  2. milanvarady commented on Dec 31, 2024

    @milanvarady
    Author

    Sure. If that's easier to implement than a closure, it's equally elegant I think.

  3. Dean151 commented on Dec 31, 2024

    @Dean151
    Owner

    Sure. If that's easier to implement than a closure, it's equally elegant I think.

    It's not easier to implement, but I find the pattern better suited for an optional closure than making that a standard stuff that would be for all the init() overrides out there

  4. self-assigned this
    on Dec 31, 2024
  5. Dean151 commented on Jan 12, 2025

    @Dean151
    Owner

    Rethinking about it, I wonder what you have against the currently supported format:

    AsyncButton {
        do {
            try await longOperation()
        } catch {
            // Do something with error
            throw error
        }
    } label: {
        Label("Long Operation", systemImage: "clock")
    }

    Catching to re-throw is a pretty common pattern

  6. milanvarady commented on Jan 12, 2025

    @milanvarady
    Author

    It's just that almost all of my async functions are throwing and I thought it would be cleaner to do it the way I suggested.

  7. Dean151 commented on Jan 12, 2025

    @Dean151
    Owner

    I see an advantage with the modifier, is that you can deal with the error of multiple buttons at the same time:

    Group {
        AsyncButton { ... } label: { ... }
        AsyncButton { ... } label: { ... }
        AsyncButton { ... } label: { ... }
    }
    .onButtonError { error in
          // Do something with the error
          print(error)
    }

    I'll implement that for version 0.6.0

  8. milanvarady commented on Jan 12, 2025

    @milanvarady
    Author

    Thats actually pretty nice. Thanks.

  9. added a commit that references this issue on Jan 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions