1

I'm using the parse_declaration_list function from tinycss2 which parses css. When I give it invalid css it returns [< ParseError invalid>]. However, I can't for the life of me figure out how to actually catch this error.

I've tried:

try:
    parse_declaration_list(arg)
except:
    do_something()

no dice.

try:
    parse_declaration_list(arg)[0]
except:
    do_something()

nope.

try:
    parse_declaration_list(arg)
except ParseError:
    do_something()

still nothing

error = parse_declaration_list(arg)[0]
if isinstance(error, Exception):
    do_something()

Sorry, no can do. I'm completely stumped and everything I google comes up with stuff about normal, well behaved errors.

vorpal
  • 268
  • 4
  • 17

1 Answers1

1

The documentation indicates that the error is not raised, but returned, i.e. try/except won't work here. Instead, you have to check the result, as you do in your last approach. However, ParseError seems not to be a subclass of Exception. Also, you probably can't just check the first element of the list. You can try something like this (not tested):

result = parse_declaration_list(arg)
if any(isinstance(r, tinycss2.ast.ParseError) for r in result):
    do_something()
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • Thank you! I almost go there. I'd tried "isinstance(result, tinycss2.ast.ParseError)", but it didn't work so I gave up on that tack. – vorpal Oct 04 '17 at 13:42