Handle errors when parsing XML
This commit is contained in:
parent
dc0f5964a9
commit
a36dcc9535
|
@ -12,16 +12,23 @@ defmodule FeedParser.Parser.Atom do
|
||||||
def accepts(data, content_type) do
|
def accepts(data, content_type) do
|
||||||
case content_type do
|
case content_type do
|
||||||
"application/atom+xml" ->
|
"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"] ->
|
_ when content_type in ["text/xml", "application/xml"] ->
|
||||||
doc = XML.parse(data)
|
case XML.parse(data) do
|
||||||
|
{:error, _} ->
|
||||||
|
false
|
||||||
|
|
||||||
|
{:ok, doc} ->
|
||||||
if XML.xmlElement(doc, :name) == :feed do
|
if XML.xmlElement(doc, :name) == :feed do
|
||||||
{true, doc}
|
{true, doc}
|
||||||
else
|
else
|
||||||
false
|
false
|
||||||
end
|
end
|
||||||
|
end
|
||||||
|
|
||||||
_ ->
|
_ ->
|
||||||
false
|
false
|
||||||
|
|
|
@ -12,16 +12,23 @@ defmodule FeedParser.Parser.RSS2 do
|
||||||
def accepts(data, content_type) do
|
def accepts(data, content_type) do
|
||||||
cond do
|
cond do
|
||||||
content_type in ["application/rss+xml", "text/rss+xml"] ->
|
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"] ->
|
content_type in ["text/xml", "application/xml"] ->
|
||||||
doc = XML.parse(data)
|
case XML.parse(data) do
|
||||||
|
{:error, _} ->
|
||||||
|
false
|
||||||
|
|
||||||
|
{:ok, doc} ->
|
||||||
if XML.xmlElement(doc, :name) == :rss do
|
if XML.xmlElement(doc, :name) == :rss do
|
||||||
{true, doc}
|
{true, doc}
|
||||||
else
|
else
|
||||||
false
|
false
|
||||||
end
|
end
|
||||||
|
end
|
||||||
|
|
||||||
true ->
|
true ->
|
||||||
false
|
false
|
||||||
|
|
|
@ -9,12 +9,16 @@ defmodule FeedParser.XML do
|
||||||
defrecord :xmlAttribute, extract(:xmlAttribute, from_lib: "xmerl/include/xmerl.hrl")
|
defrecord :xmlAttribute, extract(:xmlAttribute, from_lib: "xmerl/include/xmerl.hrl")
|
||||||
defrecord :xmlText, extract(:xmlText, 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
|
def parse(data) do
|
||||||
{doc, _} =
|
{doc, _} =
|
||||||
|
try do
|
||||||
data
|
data
|
||||||
|> :binary.bin_to_list()
|
|> :binary.bin_to_list()
|
||||||
|> :xmerl_scan.string()
|
|> :xmerl_scan.string()
|
||||||
|
catch
|
||||||
|
:exit, reason -> {:error, "parsing XML failed: #{inspect(reason)}"}
|
||||||
|
end
|
||||||
|
|
||||||
doc
|
doc
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in New Issue