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.
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).
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 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“.
You need more than one Spring module to accomplish this. The basic steps are:
@ControllerAdvice
that catches the custom exception and translates it into an HTTP 404
status code.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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With