Class ResourceNotFoundException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
com.example.springrest.exceptions.ResourceNotFoundException
- All Implemented Interfaces:
Serializable
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 Summary
ConstructorsConstructorDescriptionResourceNotFoundException
(String message) Constructs a newResourceNotFoundException
with the specified detail message. -
Method Summary
Methods inherited from class java.lang.Throwable
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
-
Constructor Details
-
ResourceNotFoundException
Constructs a newResourceNotFoundException
with the specified detail message.- Parameters:
message
- a descriptive message explaining the cause of the exception.
-