Search code examples
httpspring-boothttpresponse

Return 404 for every null response


I'd like to return 404 when the response object is null for every response automatically in spring boot.

I need suggestions.

I don't want to check object in controller that it is null or not.


Solution

  • You need more than one Spring module to accomplish this. The basic steps are:

    1. Declare an exception class that can be used to throw an exception when a repository method does not return an expected value.
    2. Add a @ControllerAdvice that catches the custom exception and translates it into an HTTP 404 status code.
    3. Add an AOP advice that intercepts return values of repository methods and raises the custom exception when it finds the values not matching expectations.

    Step 1: Exception class

    public class ResourceNotFoundException extends RuntimeException {}
    

    Step 2: Controller advice

    @ControllerAdvice
    public class ResourceNotFoundExceptionHandler
    {
      @ExceptionHandler(ResourceNotFoundException.class)
      @ResponseStatus(HttpStatus.NOT_FOUND)
      public void handleResourceNotFound() {}
    }
    

    Step 3: AspectJ advice

    @Aspect
    @Component
    public class InvalidRepositoryReturnValueAspect
    {
      @AfterReturning(pointcut = "execution(* org.example.data.*Repository+.findOne(..))", returning = "result")
      public void intercept(final Object result)
      {
        if (result == null)
        {
          throw new ResourceNotFoundException();
        }
      }
    }
    

    A sample application is available on Github to demonstrate all of this in action. Use a REST client like Postman for Google Chrome to add some records. Then, attempting to fetch an existing record by its identifier will return the record correctly but attempting to fetch one by a non-existent identifier will return 404.