grailsgrails-2.0grails-services

Is it possible for a service to return a 404 response?


Is there an exception or something else that can be raised from a service (or other non-Controller method) that will interrupt the current response handling and return a 404 to the user?

In the Django world, there is get_object_or_404 which raises a Http404 exception which has this effect. I'm writing service; if that service determines that the object requested is not accessible to the user (in this case it's not published yet), I would like it to trigger a 404 and stop the remainder of the execution. The goals is for the controllers calling the service to be DRY and not always repeat the def obj = someService.getSomething(); if (obj) {} else { render status: 404} call.

Summary:
In Django, I can raise a Http404 at any point to stop request processing and return a 404. Is there an equivalent or a way to do this in Grails NOT from a controller?


Solution

  • Create an Exception class like com.my.ResourceNotFoundException and then throw it from whatever place you want (controller or service).

    Create a controller like the one below:

    class ErrorController {
    
        def error404() {
            response.status = HttpStatus.NOT_FOUND.value()
            render([errors: [[message: "The resource you are looking for could not be found"]]] as JSON)
        }
    }
    

    Then add into your UrlMappings.groovy configuration file an entry that will handle exceptions of that type with this controller action. Specifying "500" as the pattern means that it will catch 500 errors (like the one your thrown ResourceNotFoundException will cause) and if the exception matches that type it will use the controller and action specified.

    "500"(controller: "error", action: "error404", exception: ResourceNotFoundException)