在Grails服务中处理错误和消息的最佳方法

时间:2013-07-11 16:19:14

标签: spring grails

我有一个Grails应用程序,我想知道将错误和消息从我的服务层传递给控制器​​的最佳方法。例如,假设我单击我的应用程序中的一个调用服务的链接并将我带到一个新页面。在我的应用程序中的新页面上,我希望看到如下消息列表:

Information: 10 files processed successfully.

Warning: FileA is missing CreationDate

Error: FileB failed processing
Error: FileC failed processing
Error: FileD failed processing

我知道我可以创建一个自定义对象,例如“ServiceReturnObject”,其属性如:

def data
def errors
def warnings
def information

让我的所有服务都返回此对象。

我也知道我可以使用异常,但我不确定这是否是具有多个异常和多种异常类型的正确解决方案。

这里的最佳做法是什么?示例会有所帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

要返回错误,我会创建一个自定义异常类,并使用它来包装服务可以生成的所有其他错误。这样,您只需要捕获有限数量的异常。如果你有多个需要返回错误的控制器方法/闭包,我会将代码考虑在内:

首先,创建您的异常类并将其放在正确的命名空间中的src / java中:

class MyException extends Exception {
    protected String code; // you could make this an int if you want
    public String getCode() { return code; }

    public MyException(String code, String message) {
        super(message);
        this.code = code;
    }
}

现在,在您的控制器中,创建一个错误处理方法并将所有调用包装在其中

class MyController {
    def myService;

    def executeSafely(Closure c) {
        Map resp = [:]
        try {
            resp.data = c();
        }
        catch(MyException myEx) {
            resp.error = myEx.getMessage();
            resp.code = myEx.getCode();
        }
        catch(Exception ex) {
            resp.error = 'Unexpected error: ' + ex.getMessage();
            resp.code = 'foo';
        }

        return resp;
    }


    def action1 = {
        def resp = executeSafely {
            myService.doSomething(params);
        }

        render resp as JSON;
    }

    def action2 = {
        def resp = executeSafely {
            myService.doSomethingElse(params);
        }

        render resp as JSON;
    }
}

或者,您可以让executeSafely将响应转换为JSON,然后直接呈现它。