-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathDDError.swift
70 lines (63 loc) · 2.55 KB
/
DDError.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-2020 Datadog, Inc.
*/
import Foundation
/// Common representation of Swift `Error` used by different features.
internal struct DDError: Equatable {
/// Common error key encoding threads information in Crash Reporting.
/// See "RFC - iOS Crash Reports Minimization" for more context.
static let threads = "error.threads"
/// Common error key encoding binary images information in Crash Reporting.
/// See "RFC - iOS Crash Reports Minimization" for more context.
static let binaryImages = "error.binary_images"
/// Common error key encoding crash meta information in Crash Reporting.
/// See "RFC - iOS Crash Reports Minimization" for more context.
static let meta = "error.meta"
/// Common error key encoding boolean flag - `true` if any stack trace was truncated, otherwise `false`.
/// See "RFC - iOS Crash Reports Minimization" for more context.
static let wasTruncated = "error.was_truncated"
let type: String
let message: String
let stack: String
}
extension DDError {
init(error: Error) {
if isNSErrorOrItsSubclass(error) {
let nsError = error as NSError
self.type = "\(nsError.domain) - \(nsError.code)"
if nsError.userInfo[NSLocalizedDescriptionKey] != nil {
self.message = nsError.localizedDescription
} else {
self.message = nsError.description
}
self.stack = "\(nsError)"
} else {
let swiftError = error
self.type = "\(Swift.type(of: swiftError))"
self.message = "\(swiftError)"
self.stack = "\(swiftError)"
}
}
}
private func isNSErrorOrItsSubclass(_ error: Error) -> Bool {
var mirror: Mirror? = Mirror(reflecting: error)
while mirror != nil {
if mirror?.subjectType == NSError.self {
return true
}
mirror = mirror?.superclassMirror
}
return false
}
internal extension HTTPURLResponse {
func asClientError() -> Error? {
// 4xx Client Errors
guard statusCode >= 400 && statusCode < 500 else {
return nil
}
let message = "\(statusCode) " + HTTPURLResponse.localizedString(forStatusCode: statusCode)
return NSError(domain: "HTTPURLResponse", code: statusCode, userInfo: [NSLocalizedDescriptionKey: message])
}
}