@@ -60,30 +60,7 @@ internal extension HTMLSAXParser {
6060 htmlCtxtUseOptions ( parserContext, options)
6161
6262 let parseResult = htmlParseDocument ( parserContext)
63- let parseSuccess = parseResult == 0
64- if !parseSuccess {
65- guard let error = handlerContext. lastError ( ) ,
66- let errorLevel = ErrorLevel ( rawValue: Int ( error. pointee. level. rawValue) ) else {
67- return
68- }
69-
70- switch errorLevel {
71- case . fatal:
72- let message : String
73- if let messageCString = error. pointee. message {
74- message = String ( cString: messageCString)
75- }
76- else {
77- message = " "
78- }
79-
80- let location = Location ( line: Int ( error. pointee. line) , column: Int ( error. pointee. int2) )
81-
82- throw Error . parsingFailure ( level: errorLevel, location: location, message: message)
83- case . none, . warning, . error:
84- break
85- }
86- }
63+ try handleParseResult ( parseResult, handlerContext)
8764
8865 }
8966 }
@@ -140,6 +117,45 @@ internal extension HTMLSAXParser {
140117 }
141118 }
142119
120+ /**
121+ Handle the parse result from the underlying libxml2 htmlParseDocument call. Determines if the parse method
122+ should throw a parsingFailure error. This will check the result did not end with a fatal error. Other less
123+ serious error levels will be considered a success.
124+
125+ One success the method returns, otherwise the method throws an `HTMLParser.Error`
126+
127+ - Parameter parseResult: The result from the libxml2 htmlParseDocument call.
128+ - Parameter handlerContext: The handler context.
129+ - Throws: `HTMLParser.Error` if the parsing ended with a fatel error.
130+ */
131+ private func handleParseResult( _ parseResult: Int32 , _ handlerContext: HTMLSAXParser . HandlerContext ) throws {
132+ // htmlParseDocument returns zero for success, therefore if non-zero we need to check the last error.
133+ if parseResult != 0 {
134+ guard let error = handlerContext. lastError ( ) ,
135+ let errorLevel = ErrorLevel ( rawValue: Int ( error. pointee. level. rawValue) ) else {
136+ // If no last error was found or the error level has invalid value then just return.
137+ return
138+ }
139+
140+ switch errorLevel {
141+ case . fatal: // if fatal then throw a parsingFailure
142+ let message : String
143+ if let messageCString = error. pointee. message {
144+ message = String ( cString: messageCString) . trimmingCharacters ( in: . whitespacesAndNewlines)
145+ }
146+ else {
147+ message = " "
148+ }
149+
150+ let location = Location ( line: Int ( error. pointee. line) , column: Int ( error. pointee. int2) )
151+
152+ throw Error . parsingFailure ( level: errorLevel, location: location, message: message)
153+ case . none, . warning, . error: // All other levels of error will be considered success
154+ break
155+ }
156+ }
157+ }
158+
143159 private class HandlerContext : HTMLSAXParseContext {
144160
145161 let handler : EventHandler
0 commit comments