Xcode not displaying text of error from custom editor extension

179 Views Asked by At

I have created a custom Xcode editor extension that can fail to run if certain conditions have not been met.

Specifically, it's a Sort Lines command and will refuse to run if there is more than one selection, or if the selection has fewer than two lines.

I have defined an Error-conforming enum to define my errors that also conforms to LocalizedError.

enum CommandError: Error, LocalizedError
{
  case notEnoughLines
  case tooManySelections

  public var errorDescription: String?
  {
    switch self
    {
    case .notEnoughLines:     return NSLocalizedString("Not enough lines to sort", comment: "notEnoughLines")
    case .tooManySelections:  return NSLocalizedString("Too many selections", comment: "tooManySelections")        
    }
  }
}

In my perform(with:completionHandler:) method I call the completion handler with one of the errors as appropriate:

...
if invocation.buffer.selections.count > 1
{
  completionHandler(CommandError.tooManySelections)
  return
} 
...

I am expecting the text of the error ("Too many selections") to be displayed. Instead, the error is displayed as:

The operation couldn't be completed. (Ext01.SortLinesCommand.CommandError error 1.)

Am I doing this incorrectly, or is this an issue in XcodeKit or Xcode?

1

There are 1 best solutions below

1
Dominik Bucher On

I have created an Article for Xcode extension on my linkedIn profile. The issue in here is that the Error is protocol and NSError is object. You mustn't pass Error protocol to the completion handler but you must pass NSError instance in there. Was a bit confused before too.

if you create NSError instance like this

  var userInfo: [AnyHashable : Any] = [
        NSLocalizedDescriptionKey :  NSLocalizedString(
            "Finally! This works!",
            value: "Finally! This works!",
            comment: ""
        ),
        NSLocalizedFailureReasonErrorKey : NSLocalizedString(
            "Finally! This works!",
            value: "Finally! This works!",
            comment: ""
        )
    ]

 let error = NSError(
    domain: "", 
    code: 666,
    userInfo: userInfo
  )
  // And pass it to completion like this, it will work
  completionHandler(error)

Check my article for further understanding of this problem:

https://www.linkedin.com/pulse/xcode-extension-defining-enum-variables-swift-moreerror-bucher/

If you are curious just about the errors, Cmd+f on the article this keywords:

I haven't seen any extension with passing error