===================================== How to handle exceptions in REST API ===================================== => We will use below 2 annotation to handle exceptions in rest api 1) @ExceptionHandler (method level annotation) 2) @RestControllerAdvice (class level annotation) => We can handle exceptions in 2 ways 1) Class based Exception Handling 2) Global Exception Handling => Class based exception handling means it will handle exceptions related to particular class only. ``` @Data public class ExInfo { private String exCode; private String exMsg; private LocalDateTime exDate; } ``` @RestController public class MsgRestController { @GetMapping("/welcome") public ResponseEntity getWelcomeMsg() { String msg = "Welcome To Ashok IT"; int i = 10 / 0; return new ResponseEntity<>(msg, HttpStatus.OK); } @ExceptionHandler(exception = Exception.class) public ResponseEntity handleEx(Exception e) { ExInfo exInfo = new ExInfo(); exInfo.setExCode("EX000002"); exInfo.setExMsg(e.getMessage()); exInfo.setExDate(LocalDateTime.now()); return new ResponseEntity<>(exInfo, HttpStatus.INTERNAL_SERVER_ERROR); } } ``` Note: If we write Exception Handler method inside rest controller then it is called as Class based exception Handling. => Global Exception handling means it will handle excetions related to all the classes available in the application. Note: If we write Exception Handler method inside @RestControllerAdvice class then it is called as Global Exception handling. ``` public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String msg) { super(msg); } } ``` @RestControllerAdvice public class AppExHandler { @ExceptionHandler(exception = UserNotFoundException.class) public ResponseEntity handleUserNotFoundEx(UserNotFoundException e) { ExInfo exInfo = new ExInfo(); exInfo.setExCode("EX000001"); exInfo.setExMsg(e.getMessage()); exInfo.setExDate(LocalDateTime.now()); return new ResponseEntity<>(exInfo, HttpStatus.BAD_REQUEST); } @ExceptionHandler(exception = SQLException.class) public ResponseEntity handleSQLEx(SQLException e) { ExInfo exInfo = new ExInfo(); exInfo.setExCode("EX000003"); exInfo.setExMsg(e.getMessage()); exInfo.setExDate(LocalDateTime.now()); return new ResponseEntity<>(exInfo, HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(exception = Exception.class) public ResponseEntity handleEx(Exception e) { ExInfo exInfo = new ExInfo(); exInfo.setExCode("EX000002"); exInfo.setExMsg(e.getMessage()); exInfo.setExDate(LocalDateTime.now()); return new ResponseEntity<>(exInfo, HttpStatus.INTERNAL_SERVER_ERROR); } } ``` ======================================== 1) application.properties vs application.yml 2) How to read properties from yml file into java class to remove hard coding 3) RestRepositories ============================================