Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know from where was thrown error 500 (Grails)

I have the next scenario in my UrlMappings.groovy:

"/user/$action?" (controller:"user")
"/admin/$action?" (controller:"user")

"500"(controller:"error", action:"show")
"404"(controller:"error", action:"show")

And I need to know on the errorController from which controller was thrown the exception (if any) that raises the error 500, and show diferent error pages for users and admin.

Any ideas?

Thanks in advance.

like image 568
David Santamaria Avatar asked Mar 30 '11 19:03

David Santamaria


2 Answers

You can access the exception in your ErrorController via request.exception. The top level exception always points to the controller where it was thrown so you can find out the controller name with exception.className. Here's a very simple example.

class ErrorController {

    def show = {
      def exception = request.exception
      render(text: "Exception in ${exception?.className}", 
        contentType: "text/plain", encoding: "UTF-8")
    }
}
like image 54
Aoi Karasu Avatar answered Oct 16 '22 07:10

Aoi Karasu


Using request.getAttribute("exception") you'll have the exception at your hand. I'd take a look at all request attributes, maybe there's a direct reference to the originating controller.

UPDATE

The trick is that Grails wraps the thrown exception into a GrailsWrappedRuntimeException providing comfortable access to the code being responsible for the exception. Use the following snippet in your error controller:

import org.codehaus.groovy.grails.web.errors.GrailsWrappedRuntimeException
def action = {   
   def exception = request.getAttribute('exception')
   if (exception instanceof GrailsWrappedRuntimeException) {
       log.error "exception $exception.className, line $exception.lineNumber has throw $exception.cause"
   }
}
like image 39
Stefan Armbruster Avatar answered Oct 16 '22 07:10

Stefan Armbruster