Function map_error

Source
pub fn map_error<'a, Toks, T, A, P, F>(
    p: P,
    f: F,
) -> impl Parser<'a, Toks, T, A>
where Toks: Tokens<T> + 'a, T: Clone + Debug, P: Parser<'a, Toks, T, A> + 'a, F: Fn(ParseError<Toks, T>) -> ParseError<Toks, T> + 'a,
Expand description

Changes the given parser’s error value with the provided function.

This function provides another option for modifying the error values of failed parsers, as using a function like this may be more convinient than manually matching against ParseResults.

Note: this function explicitly prohibits the modification/replacement of error values created with the ParseError::other function, as such errors were caused by factors outside of the parser chain. However, this function does not prohibit the creation of such error values.

See also: ParseError, map_error_details.

§Examples

use bad_parsers::{Parser, ParseError, token};

let p1 = token('a');
let p2 = token('a').map_error(|mut e| {
    e.overwrite_details("custom message");
    e
});

// Fails with default error message
let expected1 = "Parsing was unsuccessful (couldn't find token: 'a'), Failed at: \"b\"";
let msg1 = p1.parse("b").unwrap_err().to_string();
// Fails with custom error message
let expected2 = "Parsing was unsuccessful (custom message), Failed at: \"b\"";
let msg2 = p2.parse("b").unwrap_err().to_string();

assert_eq!(expected1, msg1);
assert_eq!(expected2, msg2);