i have grails app, , want know best way pass errors , messages service layer controller. example, click link in app calls service , brings me new page. on new page in application, want see list of messages so:
information: 10 files processed successfully. warning: filea missing creationdate error: fileb failed processing error: filec failed processing error: filed failed processing
i know can create custom object "servicereturnobject" properties like:
def data def errors def warnings def information
and have of services return object.
i know can use exceptions, not sure if right solution multiple exceptions , multiple types of exceptions.
what best practice here? examples helpful, thanks.
to return errors, create custom exception class, , use wrap other errors service can generate. way, need catch limited number of exceptions. if have more 1 controller method/closure needs return errors, factor code this:
first, create exception class , put in src/java in right namespace:
class myexception extends exception { protected string code; // make int if want public string getcode() { return code; } public myexception(string code, string message) { super(message); this.code = code; } }
now, in controller, create error-handling method , wrap calls in it
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 json; } def action2 = { def resp = executesafely { myservice.dosomethingelse(params); } render resp json; } }
alternatively, can have executesafely
convert response json , render directly.
Comments
Post a Comment