Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 229
Tugrul Avatar asked May 10 '17 09:05

Tugrul


People also ask

Should a non existent page always return 404?

404s should not always be redirected. 404s should not be redirected globally to the home page. 404s should only be redirected to a category or parent page if that's the most relevant user experience available. It's okay to serve a 404 when the page doesn't exist anymore (crazy, I know).

How do I return a 404 response code?

Open or create the . htaccess-file and enter the relative path to the error page. First though, you have to create the error page (404. html, for example) on the first level of your website (the root-directory).

When should HTTP 404 be returned?

When a user requests a nonexistent URL on your website, you should return an individual error page that lets them know that the requested URL does not exist. You should also make sure that the server returns the correct HTTP status code “404“.


1 Answers

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.

like image 135
manish Avatar answered Sep 27 '22 15:09

manish