First need to create a trait Groovy file as follows under src/groovy:
trait CustomExceptionHandler { /* Handle common exception */ def handleException(Exception e) { handleCustomException(new CustomException(e.getMessage())) } /* Handle defined custom exception */ def handleCustomException2(CustomException2 e) { handleCustomException(e) } /* Handle defined custom exception */ def handleCustomException(CustomException e) { if (!CommonUtils.request) { // do something } else { CommonUtils.currentResponse.status = 220 (Custom response code) if(e.getStatusCode()) { CommonUtils.currentResponse.status = e.getStatusCode() } if (CommonUtils.request.xhr) { def error = [ type: "error", message: e.getMessage() ] render error as JSON } else { render(view: "/error/error", model: [exception: e]) } } } }
Create a groovy class under src/groovy:
import org.springframework.web.context.request.RequestContextHolder class CommonUtils { public static def getRequest() { def request = RequestContextHolder.getRequestAttributes() return request ? request.request : null } public static HttpServletResponse getCurrentResponse() { return WebUtils.retrieveGrailsWebRequest().getCurrentResponse() } }
Exception Types (Reside in src/groovy):
class CustomException extends RuntimeException { } class CustomException2 extends CustomException { }
How controller can use this feature:
class Controller1 implements CustomExceptionHandler { def index() { throw new Exception("Common exception") } def index2() { throw new CustomException("Defined custom exception") } def index3() { someService.index3() } def index4() { someService.index4() } }
Exception thrown from service bahave same as from controller
class SomeService { def index3() { throw new Exception("Common exception") } def index4() { throw new CustomException("Defined custom exception") } }