Add custom errors example (#1151)

* Add example of custom error

* Add custom_errors.rs link to documentation
This commit is contained in:
Antoine Cezar 2020-05-30 11:55:38 +02:00 committed by GitHub
parent 4a95dfa532
commit e766634631
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 45 additions and 0 deletions

View File

@ -87,6 +87,9 @@ expected '}', found 1
^
```
See [examples/custom_error.rs](https://github.com/Geal/nom/blob/master/examples/custom_error.rs)
for an example of example of implementing your custom errors.
## Debugging parsers
While you are writing your parsers, you will sometimes need to follow

42
examples/custom_error.rs Normal file
View File

@ -0,0 +1,42 @@
extern crate nom;
use nom::error::ErrorKind;
use nom::error::ParseError;
use nom::Err::Error;
use nom::IResult;
#[derive(Debug, PartialEq)]
pub enum CustomError<I> {
MyError,
Nom(I, ErrorKind),
}
impl<I> ParseError<I> for CustomError<I> {
fn from_error_kind(input: I, kind: ErrorKind) -> Self {
CustomError::Nom(input, kind)
}
fn append(_: I, _: ErrorKind, other: Self) -> Self {
other
}
}
fn parse(input: &str) -> IResult<&str, &str, CustomError<&str>> {
Err(Error(CustomError::MyError))
}
#[cfg(test)]
mod tests {
use super::parse;
use super::CustomError;
use nom::Err::Error;
#[test]
fn it_works() {
let err = parse("").unwrap_err();
match err {
Error(e) => assert_eq!(e, CustomError::MyError),
_ => panic!("Unexpected error: {:?}", err),
}
}
}