swift - Catch multiple errorTypes? -
i'm looking way catch multiple types of errors in catch. i've tried fallthrough , comma separated style switch statement , neither works. docs nothing catching multiple pattern 1. it's not clear me of pattern syntaxes work here.
error definitions (sample):
enum apperrors { case notfound(objecttype: string, id: int) case alreadyused } works:
do { //... } catch apperrors.notfound { makenewone() } catch apperrors.alreadyused { makenewone() } catch { print("unhandled error: \(error)") } does not compile, possible this?
do { //... } catch apperrors.notfound, apperrors.alreadyused { makenewone() } catch { print("unhandled error: \(error)") }
if want catch apperrors, can use pattern:
catch apperrors if you're looking more specific matching, seems ugly.
this let catch specific cases of apperrors:
catch let error apperrors error == .notfound || error == .alreadyused there's syntax seems work:
catch let error apperrors [.notfound, .alreadyused].contains(error) for completeness sake, i'll add option, allows catch errors of 2 different types, doesn't allow specify case within types:
catch let error error apperrors || error nserror finally, based on fact anything catch conform errortype protocol, can clean second & third examples provided errortype extension , use in conjunction where clause in our catch:
extension errortype { var isfooerror: bool { guard let err = self as? apperrors else { return false } return err == .notfound || err == .alreadyused } } and catch this:
catch let error error.isfooerror
Comments
Post a Comment