diff --git a/Sources/Kanna/libxmlHTMLDocument.swift b/Sources/Kanna/libxmlHTMLDocument.swift index 4a19613..6431d53 100755 --- a/Sources/Kanna/libxmlHTMLDocument.swift +++ b/Sources/Kanna/libxmlHTMLDocument.swift @@ -209,7 +209,7 @@ final class libxmlHTMLDocument: HTMLDocument { throw ParseError.EncodingMismatch } - rootNode = libxmlHTMLNode(document: self, docPtr: docPtr) + rootNode = try libxmlHTMLNode(document: self, docPtr: docPtr) } deinit { @@ -299,7 +299,7 @@ final class libxmlXMLDocument: XMLDocument { } let url: String = "" docPtr = cur.withUnsafeBytes { xmlReadDoc($0.bindMemory(to: xmlChar.self).baseAddress!, url, charsetName, CInt(option)) } - rootNode = libxmlHTMLNode(document: self, docPtr: docPtr!) + rootNode = try libxmlHTMLNode(document: self, docPtr: docPtr!) } deinit { diff --git a/Sources/Kanna/libxmlHTMLNode.swift b/Sources/Kanna/libxmlHTMLNode.swift index 84cec79..1ab4a7c 100755 --- a/Sources/Kanna/libxmlHTMLNode.swift +++ b/Sources/Kanna/libxmlHTMLNode.swift @@ -138,10 +138,15 @@ final class libxmlHTMLNode: XMLElement { } } - init(document: XMLDocument?, docPtr: xmlDocPtr) { + init(document: XMLDocument?, docPtr: xmlDocPtr) throws { self.weakDocument = document self.docPtr = docPtr - self.nodePtr = xmlDocGetRootElement(docPtr) + guard let nodePtr = xmlDocGetRootElement(docPtr) else { + // Error handling is omitted, and will be added if necessary in the future. + // e.g: if let error = xmlGetLastError(), error.pointee.code == XML_ERR_DOCUMENT_EMPTY.rawValue + throw ParseError.Empty + } + self.nodePtr = nodePtr } init(document: XMLDocument?, docPtr: xmlDocPtr, node: xmlNodePtr) { diff --git a/Tests/KannaTests/KannaHTMLTests.swift b/Tests/KannaTests/KannaHTMLTests.swift index c0ce5a2..efe5289 100755 --- a/Tests/KannaTests/KannaHTMLTests.swift +++ b/Tests/KannaTests/KannaHTMLTests.swift @@ -153,6 +153,16 @@ class KannaHTMLTests: XCTestCase { XCTAssert(previous.text == "first") } + func testEmptyHTML() { + XCTAssertThrowsError(try HTML(html: "", encoding: .utf8)) { error in + XCTAssertEqual(error as? ParseError, ParseError.Empty) + } + + XCTAssertThrowsError(try HTML(html: " ", encoding: .utf8)) { error in + XCTAssertEqual(error as? ParseError, ParseError.Empty) + } + } + func testEscapeId() { let html = "