Spring Boot Exception Handling
Mohamad's interest is in Programming (Mobile, Web, Database and Machine Learning). He is studying at the Center For Artificial Intelligence Technology (CAIT), Universiti Kebangsaan Malaysia (UKM).
Implementing Global Exception Handling:
- Use
@ControllerAdviceand@ExceptionHandlerto handle exceptions globally.
Example: Custom Exception for Resource Not Found
Create a
ResourceNotFoundExceptionClass:java
package com.example.demo; public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } }Handle Exception in Controller:
java
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/products") public class ProductController { @Autowired private ProductRepository productRepository; @GetMapping("/{id}") public ResponseEntity<Product> getProduct(@PathVariable Long id) { Product product = productRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("Product not found")); return ResponseEntity.ok(product); } // Other CRUD methods... }Create a Global Exception Handler:
java
package com.example.demo; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND); } // Other exception handlers... }