English 中文(简体)
如何使用scala组合解析器将异常与有意义的消息一起抛出?
原标题:how do i throw exceptions with meaningful messages with a scala combination parser?

当语言不符合scala组合解析器的语法时,我想抛出一个异常。以下是一个规则示例:

def record: Parser[Record] = "-" ~ opt(recordLabel) ~ repsep(column, ",") ^^ {
    case "-" ~ label ~ columns => new Record(label, columns)
}

假设在repsep(column,“,”)部分,他们意外地生成了这样的字符串

a, b, c, d,

这是无效的,因为它以一个“,”结尾,而这个“,”不应该存在。与其说解析器在调用parseAll()时停止,不如说如何使它抛出一个可读的有意义的异常?(自定义文本、行号等)

编辑:好吧,我发现了一些有效的东西,但我对它的可定制性不满意:

def loadFrom(filename: String) {
    val source = 
        Source.fromFile(filename).getLines.mkString("
")
    val parseResult = parseAll(tables, source)
    if(!parseResult.successful) {
        throw new TestDataParseException(parseResult.toString)
    }
}

toString会打印一条OK消息,但当它找到一个空间时,它会打印一些奇怪的东西,比如想要“z”(有时在我的IDE中看起来像一个块/正方形)。我宁愿说:“嘿,你忘了逗号!”

行号/列确实以[x.y]的形式打印出来。我实际上想显示[line:x,Column:y],因为人们会更直观地知道这是什么。

谢谢

最佳回答
parseAll(tables, source) match {
  case Success(ast, _) => //do something
  case NoSuccess(msg, next) => {
        println("Failed at line %s, column %s: %s".format(
                    next.pos.line, next.pos.column, msg))
  }
}
问题回答

暂无回答




相关问题
Parse players currently in lobby

I m attempting to write a bash script to parse out the following log file and give me a list of CURRENT players in the room (so ignoring players that left, but including players that may have rejoined)...

How to get instance from string in C#?

Is it possible to get the property of a class from string and then set a value? Example: string s = "label1.text"; string value = "new value"; label1.text = value; <--and some code that makes ...

XML DOM parsing br tag

I need to parse a xml string to obtain the xml DOM, the problem I m facing is with the self closing html tag like <br /> giving me the error of Tag mismatch expected </br>. I m aware this ...

Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

Locating specific string and capturing data following it

I built a site a long time ago and now I want to place the data into a database without copying and pasting the 400+ pages that it has grown to so that I can make the site database driven. My site ...

热门标签