0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swift Errorの使い方 エラーハンドリング

Last updated at Posted at 2022-04-16

エラーハンドリング、Errorの使い方

概要

Errorのクラスの使い道を考えてみた。

結論

下記のようなextensionを作成します。


import Foundation

extension Error {
    var domain: String {
        (self as NSError).domain
    }

    var code: Int {
        (self as NSError).code
    }

    var info: [String: String] {
        guard let userInfo = (self as NSError).userInfo as? [String: String] else { return [:] }
        return userInfo
    }
}

エラー発生時は下記のようにします。

定数

import Foundation

enum AppConstant {
    static let LocalizedSuggestion = "LocalizedSuggestion"
}

下記のようにします。

completion(.failure(NSError(domain: "Server Error",
                                                code: -10001,
                                                userInfo: [AppConstant.LocalizedSuggestion: "Http response header invalid status code: \(response.statusCode)"])))

それを呼ぶときは下記のようにします。

        api.session { error in
            DispatchQueue.main.async {
                self.alert(title: error.domain,
                           message: error.info[AppConstant.LocalizedSuggestion])
                print(error)
            }
        }

こうすることにより、Errorクラスを有意義に活用できます。
これまで様々な人のエラーハンドリング時の文言などをみてきましたが、大体はStringクラスを用いるだとか、structを用いるだとか、error.localizedDescriptionを用いるだとかが多いですが、

今回のこの方法が良いのでは無いかと思うわけであります。

Gihub gist Error+

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?