2013-03-13 76 views
1

在我的Grails Web应用程序中,我有一个弹出式对话框,允许我输入某种类型的自然语言表达式,它将用于在应用程序中执行某些操作。创建错误条件并将它们传回给客户端

我目前在groovy中实现了解析器,并想知道如何去创建错误消息并将它们返回给客户端。

我正在考虑使用<g:formRemote>,它将使用ajax将文本字符串发送到解析器,并且在成功解析字符串时,它将执行应用程序中的动作,比如将用户添加到项目中,通常跟着一个重定向到一个新页面,比如说向用户显示该项目的一部分。如果解析器收到一个令牌并不期望/识别,或者如果该字符串没有遵循正确的语法,我就可以创建一条错误消息并将其发送回客户端,从而允许用户尝试另一个命令。

到目前为止,我的代码看起来像这样..

在我的控制器接收Ajax请求

def runTemp() 
{ 
    def tokenizer = new Tokenizer() 
    def posTagger = new PartOfSpeechTagger() 

    def words = tokenizer.getTokens("add user"); 
    def taggedWords = posTagger.tagWords(words) 

    taggedWords.each{ 
     println"${it.word} : ${it.partOfSpeech}" 
    }  
} 

和我PartOfSpeechTagger.groovy看起来像

package uk.co.litecollab.quickCommandParser 

class PartOfSpeechTagger { 

def lexicons = [ 
    //VERBS 
    'add': PartOfSpeech.VERB, 
    'new': PartOfSpeech.VERB, 
    'create': PartOfSpeech.VERB, 
    'view': PartOfSpeech.VERB, 
    'delete': PartOfSpeech.VERB, 
    'logout': PartOfSpeech.VERB, 
    'remove': PartOfSpeech.VERB, 
    'chat': PartOfSpeech.VERB, 
    'accept': PartOfSpeech.VERB, 
    'active': PartOfSpeech.VERB, 
    'suspend': PartOfSpeech.VERB, 
    'construct': PartOfSpeech.VERB, 
    'close': PartOfSpeech.VERB, 
    'add': PartOfSpeech.VERB, 

    //NOUNS 
    'project': PartOfSpeech.NOUN, 
    'user': PartOfSpeech.NOUN, 
    'task': PartOfSpeech.NOUN, 
    'chat': PartOfSpeech.NOUN, 
    'conversation': PartOfSpeech.NOUN, 

    //DETERMINERS 
    'a': PartOfSpeech.DETERMINER, 
    'the': PartOfSpeech.DETERMINER, 

    //PREPOSITIONS 
    'to': PartOfSpeech.PREPOSITION, 
    'from': PartOfSpeech.PREPOSITION, 
    'for': PartOfSpeech.PREPOSITION, 
    'with': PartOfSpeech.PREPOSITION  
    ] 


//constructor 
def PartOfSpeechTagger() 
{ 

} 

def tagWords(String[] words) 
{ 
    def taggedWords = [] as ArrayList 
    words.each{ 
     //removing the use of 'it' due to nested closures 
     println"word to search for : ${it}" 
     def word = it 
     if(inLexicons(word)) 
     { 
      println"word :: ${it}" 
      taggedWords.add(
       new TaggedWord(
        lexicons.find{it.key == word}.key, 
        lexicons.find{it.key == word}.value) 
       )   
     } 
     else 
     { 
      /* 
      * handle errors for not finding a word? 
      */ 
     } 
    } 

    return taggedWords 
} 

def inLexicons(key) 
{ 
    return lexicons.containsKey(key) 
} 
} 

你可以看到tagWords方法,我希望能够向客户报告提供的单词不是预期的。

+1

因此存取这个,有什么题? – eugene82 2013-03-13 13:03:25

+0

我想知道创建错误消息的最佳方式以及将它们发送回客户端的最佳方法。我是否创建自己的例外? – 2013-03-13 13:26:07

+1

所以在ajax调用中,您可以返回错误代码和文本。例如:'response.status = 400'' render“无法匹配标签”'。 – 2013-03-13 13:35:33

回答

0

得到它的工作,

在控制器

render(status: 400, text: "the message") 

然后在我的远程形式

onFailure="doSomething(XMLHttpRequest)" 

然后在JavaScript中通过

XMLHttpRequest.responseText 
相关问题