Trigger 404 in Spring-MVC controller?
To trigger a 404 response in Spring MVC, simply throw a ResponseStatusException
accompanied with HttpStatus.NOT_FOUND
:
This clean snippet explicitly states the requested resource is nowhere to be found, leading to the inevitable: a 404 error.
Let's extend this principle to a broader scope like coupling it with a ResourceNotFoundException
.
In this example, ResourceNotFoundException
is thrown when the resources play hide and seek, with @ResponseStatus
signalling a 404 error.
Taking a deep dive in 404-triggering mechanisms
The ResponseEntity
approach
For a more fine-grained control or just to show your ninja-like precision in handling responses, ResponseEntity
comes to the rescue:
This gives you the power of an in-code crystal ball, guiding your HTTP status destiny based on validations or business logic.
The ModelAndView
method
If you prefer to render views over REST responses (because who doesn’t like a good view, right?), ModelAndView
becomes your trusty sidekick:
ModelAndView
, the superhero of encapsulation, can masquerade your model data and view name while directing your users to the right error views.
Exception Handling for Rest Controllers
For RESTful APIs, exception handlers are less rockstars and more roadies, driving your code to a cleaner stage:
With @RestControllerAdvice
and @ExceptionHandler
forming the ultimate dynamic duo, manage your exceptions in one place, creating a neat separation of responsibilities.
Circumstantially triggering 404 and adding flexibility
The flexibility of isFound()
Sometimes you might want to decide if a 404 status should be triggered based on your rules and the alignment of the planets:
Java 8's Optional API lets the isPresent
or isFound
function guide your decision, making your code compact and reducing your error-prone footprint.
The Legacy Technique
Spring versions before 3.0.2 require a more traditional approach, like a good old HttpServletResponse
:
Though a bit verbose, it offers a low-level API to manually set response status codes, reminding us of the olden days.
Checking with HttpServletRequest
In some cases, you might want to inspect the HttpServletRequest
before you blow the 404 whistle:
Analyzing HttpServletRequest
gives you that detective edge when working with distinct URL patterns.
Was this article helpful?