Handle errors when parsing XML

This commit is contained in:
Shadowfacts 2022-04-11 16:25:08 -04:00
parent dc0f5964a9
commit a36dcc9535
3 changed files with 34 additions and 16 deletions

View File

@ -12,15 +12,22 @@ defmodule FeedParser.Parser.Atom do
def accepts(data, content_type) do
case content_type do
"application/atom+xml" ->
{true, XML.parse(data)}
case XML.parse(data) do
{:error, _} -> false
{:ok, doc} -> {true, doc}
end
_ when content_type in ["text/xml", "application/xml"] ->
doc = XML.parse(data)
case XML.parse(data) do
{:error, _} ->
false
if XML.xmlElement(doc, :name) == :feed do
{true, doc}
else
false
{:ok, doc} ->
if XML.xmlElement(doc, :name) == :feed do
{true, doc}
else
false
end
end
_ ->

View File

@ -12,15 +12,22 @@ defmodule FeedParser.Parser.RSS2 do
def accepts(data, content_type) do
cond do
content_type in ["application/rss+xml", "text/rss+xml"] ->
{true, XML.parse(data)}
case XML.parse(data) do
{:error, _} -> false
{:ok, doc} -> {true, doc}
end
content_type in ["text/xml", "application/xml"] ->
doc = XML.parse(data)
case XML.parse(data) do
{:error, _} ->
false
if XML.xmlElement(doc, :name) == :rss do
{true, doc}
else
false
{:ok, doc} ->
if XML.xmlElement(doc, :name) == :rss do
{true, doc}
else
false
end
end
true ->

View File

@ -9,12 +9,16 @@ defmodule FeedParser.XML do
defrecord :xmlAttribute, extract(:xmlAttribute, from_lib: "xmerl/include/xmerl.hrl")
defrecord :xmlText, extract(:xmlText, from_lib: "xmerl/include/xmerl.hrl")
@spec parse(data :: String.t()) :: tuple()
@spec parse(data :: String.t()) :: {:ok, tuple()} | {:error, String.t()}
def parse(data) do
{doc, _} =
data
|> :binary.bin_to_list()
|> :xmerl_scan.string()
try do
data
|> :binary.bin_to_list()
|> :xmerl_scan.string()
catch
:exit, reason -> {:error, "parsing XML failed: #{inspect(reason)}"}
end
doc
end