Spring Boot Exception Handling

1 min read
Implementing Global Exception Handling:
- Use
@ControllerAdvice
and@ExceptionHandler
to handle exceptions globally.
Example: Custom Exception for Resource Not Found
Create a
ResourceNotFoundException
Class: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... }
0
Subscribe to my newsletter
Read articles from Mohamad Mahmood directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Mohamad Mahmood
Mohamad Mahmood
Mohamad's interest is in Programming (Mobile, Web, Database and Machine Learning). He studies at the Center For Artificial Intelligence Technology (CAIT), Universiti Kebangsaan Malaysia (UKM).