mirror of
https://gitee.com/openharmony/third_party_rust_nom
synced 2024-11-23 07:29:54 +00:00
Add custom errors example (#1151)
* Add example of custom error * Add custom_errors.rs link to documentation
This commit is contained in:
parent
4a95dfa532
commit
e766634631
@ -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
42
examples/custom_error.rs
Normal 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),
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user