Exception Handling
Exception Handling
• Example
@ExceptionHandler(IDNotFoundException.class)
public ResponseEntity<String> handleIdExc(IDNotFoundException e)
{
return new ResponseEntity<String>("specific exc: id not
found",HttpStatus.NOT_FOUND);
}
@RestControllerAdvice for Global Exception
Handler
• @ExceptionHandler annotated method can only handle the exceptions
thrown by that particular class.
• To handle any exception thrown throughout the application, can define
a global exception handler class and annotate it with
@ControllerAdvice.
• This annotation helps to integrate multiple exception handlers into a
single global unit.
Contd...
Example - Global Exception Handler
@RestControllerAdvice
public class GlobalException {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleArgExc(IllegalArgumentException e)
{
return new ResponseEntity<String>("global exc: id not
found",HttpStatus.BAD_REQUEST);
}
}
Exception Handling - Example Code
Develop a Spring Boot Restful Webservice that performs CRUD operations
on Customer Entity, using MYSQL database for storing all necessary data.
Step 1: Creating a JPA Entity class Customer with three fields id, name, and address.
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String address;
}
Contd...
Step 2: Creating a CustomerRepository Interface