Victor Soares
Victor Soares

Reputation: 880

Can't catch exception between services in Grails

I'm trying to catch an exception between two services but the catch code is unreachable. Does any one knows why?

Controller:

def controllerMethod() {
    try {
        service1.execute()
    } catch(CustomException ce) {
        // unreachable code
    }
}

Service 1:

def service2

def service1Method() {
    try {
        service2.execute()
    } catch(CustomException ce) {
        // unreachable code
        throw ce
    }
}

Service 2:

def service2Method() {
    throw new CustomException("exception")
}

Exception:

class CustomException extends Exception {
    CustomException(String message){
        super(message)
    }
}

Running Sample: https://bitbucket.org/victor-giacomo/grails-exception-propagation/src/master/

Upvotes: 0

Views: 70

Answers (1)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27220

See the project at github.com/jeffbrown/victorsoaresexception.

grails-app/services/victorsoaresexception/Service1Service.groovy

package victorsoaresexception

import grails.gorm.transactions.Transactional

@Transactional
class Service1Service {
    Service2Service service2Service

    def service1Method() {
        try {
            service2Service.service2Method()
        } catch(CustomException ce) {
            // unreachable code
            throw ce
        }
    }
}

grails-app/services/victorsoaresexception/Service2Service.groovy

package victorsoaresexception

class Service2Service {

    def service2Method() {
        throw new CustomException("exception")
    }
}

grails-app/controllers/victorsoaresexception/DemoController.groovy

package victorsoaresexception

class DemoController {

    Service1Service service1Service
    def controllerMethod() {
        try {
            service1Service.service1Method()
            render "No Exception  Was Thrown"
        } catch(CustomException ce) {
            render "CustomException was thrown, and caught by controller"
        }
    }
}

That all appears to work:

$ [main] http :8080/demo/controllerMethod
HTTP/1.1 200 
Connection: keep-alive
Content-Type: text/html;charset=utf-8
Date: Wed, 28 Dec 2022 18:03:39 GMT
Keep-Alive: timeout=60
Transfer-Encoding: chunked
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers

CustomException was thrown, and caught by controller


$ 

Upvotes: 1

Related Questions