Jackson ব্যবহার করে JSON ডেটা প্রসেস করার সময় Validation Error Handling এবং Custom Exception Management অত্যন্ত গুরুত্বপূর্ণ। ডেটা অনুপযুক্ত বা অসম্পূর্ণ হলে সঠিক Validation এবং Exception Handling একটি API বা অ্যাপ্লিকেশনের নির্ভরযোগ্যতা এবং নিরাপত্তা নিশ্চিত করে।
Validation Error Handling
Jackson সাধারণত Java Bean Validation বা কাস্টম লজিক দিয়ে JSON ডেটার ভ্যালিডেশন পরিচালনা করতে পারে। Java Bean Validation API (যেমন javax.validation বা jakarta.validation) এর মাধ্যমে ফিল্ডগুলোর উপর বিধিনিষেধ আরোপ করা যায়।
1. Bean Validation Integration
ডিপেন্ডেন্সি:
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.2.5.Final</version>
</dependency>
মডেল ক্লাস:
import javax.validation.constraints.*;
class User {
@NotNull(message = "ID cannot be null")
public Integer id;
@NotBlank(message = "Name cannot be blank")
public String name;
@Email(message = "Email must be valid")
public String email;
@Min(value = 18, message = "Age must be at least 18")
public int age;
}
Validation এবং Exception Handling:
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.validation.*;
import java.util.Set;
public class Main {
public static void main(String[] args) throws Exception {
String json = """
{
"id": null,
"name": " ",
"email": "invalid_email",
"age": 16
}
""";
ObjectMapper objectMapper = new ObjectMapper();
User user = objectMapper.readValue(json, User.class);
// Validate the User object
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(user);
if (!violations.isEmpty()) {
for (ConstraintViolation<User> violation : violations) {
System.out.println("Validation Error: " + violation.getMessage());
}
} else {
System.out.println("User is valid!");
}
}
}
আউটপুট:
Validation Error: ID cannot be null
Validation Error: Name cannot be blank
Validation Error: Email must be valid
Validation Error: Age must be at least 18
Custom Exception Management
Jackson JSON serialization/deserialization প্রক্রিয়ার সময় যেকোনো ত্রুটি কাস্টমাইজ করতে সক্ষম। আপনি কাস্টম Exception Handler ব্যবহার করে ত্রুটির ধরন অনুযায়ী কাস্টম মেসেজ বা লজিক সংযুক্ত করতে পারেন।
2. Custom Exception Handler
Custom Exception Class:
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
Exception Handling Example:
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
String invalidJson = """
{
"id": "invalid",
"name": "John Doe"
}
""";
try {
ObjectMapper objectMapper = new ObjectMapper();
User user = objectMapper.readValue(invalidJson, User.class);
} catch (JsonParseException e) {
throw new CustomException("JSON Parsing Error: " + e.getMessage());
} catch (JsonMappingException e) {
throw new CustomException("JSON Mapping Error: " + e.getMessage());
} catch (Exception e) {
throw new CustomException("Unknown Error: " + e.getMessage());
}
}
}
আউটপুট:
Exception in thread "main" CustomException: JSON Mapping Error: Cannot deserialize value of type `java.lang.Integer` from String "invalid": not a valid Integer value
Global Exception Handling in Spring Boot
Spring Boot-এ @RestControllerAdvice ব্যবহার করে Global Exception Handling করা যায়।
Global Exception Handler:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
public ResponseEntity<String> handleCustomException(CustomException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneralException(Exception ex) {
return new ResponseEntity<>("An unexpected error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
3. Combining Validation and Custom Exception
Spring Boot-এ Bean Validation এবং Exception Handling একত্রে ব্যবহার করা যায়।
Controller Example:
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
public ResponseEntity<String> createUser(@Valid @RequestBody User user) {
return ResponseEntity.ok("User created successfully");
}
}
Global Exception Example:
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.stream.Collectors;
@ControllerAdvice
public class ValidationExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
String errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.collect(Collectors.joining(", "));
return ResponseEntity.badRequest().body("Validation Errors: " + errors);
}
}
আউটপুট (Validation Error):
Validation Errors: id: ID cannot be null, name: Name cannot be blank, email: Email must be valid, age: Age must be at least 18
Key Takeaways:
- Validation:
- Bean Validation API দিয়ে JSON ডেটার সঠিকতা যাচাই করা যায়।
- Spring Boot-এ সরাসরি @Valid ব্যবহার করে সহজে Validation ইন্টিগ্রেট করা যায়।
- Custom Exception:
- Jackson JSON ত্রুটিগুলো কাস্টমাইজ করা যায়।
- Global Exception Handling দিয়ে অ্যাপ্লিকেশনকে আরও দৃঢ় করা যায়।
- Spring Boot Integration:
- Validation এবং Exception Handling Spring Boot-এ আরও কার্যকরভাবে ব্যবহৃত হয়।
- API তে মানসম্পন্ন ত্রুটি মেসেজ প্রদর্শন করা সহজ।
এই পদ্ধতিগুলো API ডেভেলপমেন্টে ত্রুটিমুক্ত এবং নিরাপদ ডেটা হ্যান্ডলিং নিশ্চিত করে।
Read more