Search code examples
siesta-swift

Can I use SwiftyJSON to get at error contents in Siesta?


I'm writing a test for my Siesta-based class, and I'm trying to access the error I received from the server. In my object, I configured the service like so:

    self.service.configure {
        $0.config.pipeline[.parsing].add(SwiftyJSONTransformer, contentTypes: ["*/json"])

        // other configuration setup
    }

My test contains the following:

    api.fetchApiToken(libraryRequiringAuth).onSuccess({ _ in
        // Then
        XCTFail("Expected request failure, got success")
    }).onFailure({ [weak self] (error) in
        XCTAssertEqual(error.httpStatusCode, expectedStatusCode)
        let serverError: JSON? = error.entity?.typedContent()
        XCTAssertEqual(serverError![0]["title"].string, expectedErrorMessage)
        print("Expected error is: \(error)")
        XCTAssertNil(self?.api.bearerAuthHeader)
        expectation.fulfill()
    })

The line let serverError: JSON? = error.entity?.typedContent() is setting serverError to nil, but in the debugger, I can see that error.entity exists and has the content I expect. Can I not use SwiftyJSON at this point?

Edit:

Here are the contents of the error:

Error Error(userMessage: "Forbidden", httpStatusCode: Optional(403), entity: Optional(Siesta.Entity(content: [{
    ipRangeError =     {
        libraryId = 657;
        libraryName = "Test library";
        requestIp = "my.ip.address.was_here";
    };
    status = 403;
    title = "Authentication Failed";
    userData =     {
    };
}], charset: Optional("utf-8"), headers: ["content-type": "application/json; charset=utf-8"], timestamp: 490978565.82571602)), cause: nil, timestamp: 490978565.825499)

Solution

  • It looks like your SwiftyJSONTransformer is leaving errors untouched. Try configuring it with transformErrors: true:

    private let SwiftyJSONTransformer =
      ResponseContentTransformer(transformErrors: true)
        { JSON($0.content as AnyObject) }
    

    Without that flag, the error entity is still an NSDictionary instead of a SwiftyJSON JSON, and typedContent() sees those as mismatched types and gives you a nil.

    (And to the question in the title: yes, you can get the full error content, as well as response headers and any underlying ErrorType / NSError info from the underlying networking layer.)