0

I have implemented a simple natural language parser as part of my grails app to implement a command line interface where the user can enter commands such as 'Create a new user' and the application will carry out this task etc, I have created files such as:

Tokenizer.groovy
PartOfSpeechTagger.groovy
SyntacticAnalyser.groovy
SemanticAnalyser.groovy
CommandGenerator.groovy

whereby these are placed in src/groovy

Within my controller I have a run() method that instantiates these parser classes and calls methods within these objects, like so :

 def run()
    {       
        def tokenizer = new Tokenizer()
        def posTagger = new PartOfSpeechTagger()
        def syntacticAnalyser = new SyntacticAnalyser()
        def semanticAnalyser = new SemanticAnalyser()
        def commandGenerator = new CommandGenerator()

        //split command string into tokens
        def words = tokenizer.getTokens(params.command)
          def taggedWords  = posTagger.tagWords(words)
          ... and so on
     }

My question is I want to be able to send error messages back to the client that arise within these parser classes, e.g in Tokenizer if an invalid Token is found etc.

What is the best way for me to handle these errors, and sent them back to the broswer?

I have no previous experience in error handling at this sort of level, so any input is welcomed.

Initially I have thought of throwing a custom InvalidTokenException and catching it in the controller, and rendering the text to the client, but this doesnt seem right?!

Any thoughts?

4

1 回答 1

1

您可以throw自定义异常到控制器并使用render.

//You can use whichever contentType you need, here I have mentioned json
render (status: HttpStatus.NOT_FOUND.value(), contentType: "application/json" text: exception.getMessage())

我认为我应该再分享一个观察结果。您添加的所有解析器实用程序类都src/groovy很好,但是您将以n每个实例的数量结束,以获取n来自Controller. 例如,来自控制器的单个调用最终将创建 5 ( Tokenizer, PartOfSpeechTagger, SyntacticAnalyser, SemanticAnalyser, CommandGenerator) 个实用程序类的实例。

要优化上述实现,您可以service为每个实用程序分类。由于serviceclass 默认情况下是Singleton. 每台服务器只会创建一个实例。因此,您最终将在整个应用程序中获得 5 个实用程序服务实例。

或者明确地制作实用程序类 Singleton。

只是一个你可能感兴趣的想法。

于 2013-04-28T15:58:30.800 回答