How to implement a global exception handling in Raku Cro Application

154 Views Asked by At

I am working with a rather larger Cro application with dozens of routes, models and other logic. At the moment in each route block is a CATCH to handle exception. That is not much maintenance friendly, not to speak of the work to add them. So, I was wondering if its a better way to do that. One CATCH handler in the main route block does not work. The exceptions are only caught in the route block where they are thrown. Threading issue probably. Is there one place where I can implement an exception handler which gets all exceptions and can handle them without causing the application to die?

1

There are 1 best solutions below

0
On BEST ANSWER

You can use the around function in your route block to specify something that wraps around all of the route handlers. The documentation of around gives an example of using it to handle exceptions thrown by all route handlers in the route block (repeated here for convenience):

my $application = route {
    around -> &handler {
        # Invoke the route handler
        handler();
        CATCH {
            # If any handler produces this exception...
            when Some::Domain::Exception::UpdatingOldVersion {
                # ...return a HTTP 409 Conflict response.
                conflict;
            }
        }
    }

    # Put your get, post, etc. here.
}