Return 404 for every null response

http, httpresponse, spring-boot

Solution

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

- Declare an exception class that can be used to throw an exception when a repository method does not return an expected value.

- Add a `@ControllerAdvice` that catches the custom exception and translates it into an HTTP `404` status code.

- 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`.

Problem

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.

Original source

Related problems