For unit testing purposes, I need to be able to create an NSError object with the underlyingErrors property set to a certain error.
How do you create an NSError object with underlying errors?
127 Views Asked by wristbands At
2
There are 2 best solutions below
0
On
I figured out how to do it. You have to use the userInfo field when initializing your NSError. Here's an example that creates an error that is usually thrown by FileManager when you try to delete a file that does not exist:
func createFilesystemError() -> NSError {
let underlyingNSError = NSError(domain: "NSPOSIXErrorDomain", code: 2)
let userInfo = [NSUnderlyingErrorKey: underlyingNSError]
return NSError(domain: "NSCocoaErrorDomain", code: 4, userInfo: userInfo)
}
You should always favor using the declared vars like
NSPOSIXErrorDomainorNSCocoaErrorDomaininstead of string literals. Note that there are already declaredCocoaErrorandPOSIXErrorstructs that you can use to generate those errors:But the correct way to create these erros is to initialize and cast them to
NSErrorif needed: