Class ResourceNotFoundException

java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
com.example.springrest.exceptions.ResourceNotFoundException
All Implemented Interfaces:
Serializable

@ResponseStatus(NOT_FOUND) public class ResourceNotFoundException extends RuntimeException
Exception thrown when a requested resource cannot be found.

Spring integration: Annotated with @ResponseStatus(HttpStatus.NOT_FOUND), so controllers do not need to catch it explicitly. When thrown during a request, the HTTP response code will automatically be set to 404 NOT FOUND with the exception message as the error detail.

Typical usage


 // In a service method
 public Product getOrThrow(Long id) {
     return repo.findById(id)
         .orElseThrow(() -> new ResourceNotFoundException("Product not found: " + id));
 }

 // In a controller, no try/catch needed:
 @GetMapping("/{id}")
 public ProductResponse one(@PathVariable Long id) {
     Product product = productService.getOrThrow(id);
     return mapper.toResponse(product);
 }
 

API design note: a dedicated exception class provides semantic clarity, and keeps controller code concise.

Since:
1.0
See Also:
  • Constructor Details

    • ResourceNotFoundException

      public ResourceNotFoundException(String message)
      Constructs a new ResourceNotFoundException with the specified detail message.
      Parameters:
      message - a descriptive message explaining the cause of the exception.