I can't to do something when a parser fails, in petitparser.
My solution is:
var parser = string("hello").or(
epsilon().map((_) {
// do something
}).seq(failure())
);
I want to know if there is any better solution?
Yes, this looks reasonable. The more general form
var parser = string("hello")
.or(failure("Unable to parse hello"))
is quite common.
However, introducing side-effects in parsers is normally not suggested. That said, you could create a function that encapsulates your pattern as follows:
function handleFailure(Parser parser, Function action, String message) {
return parser.or(epsilon().map(action).failure(message));
}