Exception Logging এবং Debugging Techniques

Jackson এর Error Handling এবং Exception Management - জ্যাকসন (Jackson) - Java Technologies

420

Jackson একটি শক্তিশালী JSON প্রসেসিং লাইব্রেরি হলেও, JSON serialization এবং deserialization-এর সময় বিভিন্ন ধরণের Exceptions ঘটতে পারে। সঠিক Exception Logging এবং Debugging Techniques ব্যবহার করে এসব সমস্যা দ্রুত সমাধান করা সম্ভব।


Common Jackson Exceptions এবং তাদের কারণ

  1. JsonParseException:
    • অবৈধ বা ভুল ফরম্যাটের JSON প্রসেস করার সময় ঘটে।
    • যেমন: {key: "value"} (মিসিং কোটেশনের কারণে)।
  2. JsonMappingException:
    • JSON থেকে Java Object বা Java Object থেকে JSON এ ম্যাপ করার সময় ত্রুটি।
    • যেমন: ফিল্ড মিসিং, টাইপ মিসম্যাচ।
  3. UnrecognizedPropertyException:
    • JSON-এ এমন ফিল্ড পাওয়া গেলে যা Java Object-এ নেই।
  4. InvalidDefinitionException:
    • কাস্টম Serializer/Deserializer সংজ্ঞায়িত করতে ভুল হলে।

Exception Logging এবং Debugging টেকনিক

1. Log Messages ব্যবহার করে Exception Tracking

Jackson Exception হ্যান্ডল করার সময় সঠিক লগ বার্তা সংরক্ষণ গুরুত্বপূর্ণ। Spring Boot বা Java এর Logger ব্যবহার করুন।

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JacksonLoggingExample {
    private static final Logger logger = LoggerFactory.getLogger(JacksonLoggingExample.class);

    public static void main(String[] args) {
        String invalidJson = "{ \"name\": \"John\", \"age\": \"invalid_number\" }";

        try {
            ObjectMapper mapper = new ObjectMapper();
            User user = mapper.readValue(invalidJson, User.class);
        } catch (JsonMappingException e) {
            logger.error("JSON Mapping Exception: ", e);
        } catch (JsonParseException e) {
            logger.error("JSON Parse Exception: ", e);
        } catch (Exception e) {
            logger.error("Unexpected Exception: ", e);
        }
    }
}

2. Custom Exception Messages

Custom Exception তৈরি করে আরো পরিষ্কার এবং context-specific বার্তা প্রদর্শন করা যায়।

public class CustomJsonException extends RuntimeException {
    public CustomJsonException(String message, Throwable cause) {
        super(message, cause);
    }
}
public class JacksonCustomExceptionExample {
    public static void main(String[] args) {
        String invalidJson = "{ \"name\": \"John\", \"age\": \"invalid_number\" }";

        try {
            ObjectMapper mapper = new ObjectMapper();
            User user = mapper.readValue(invalidJson, User.class);
        } catch (JsonMappingException e) {
            throw new CustomJsonException("Error mapping JSON to User object", e);
        } catch (JsonParseException e) {
            throw new CustomJsonException("Error parsing JSON input", e);
        }
    }
}

3. Enable Jackson Debugging Logs

Jackson এর ডিবাগ লগ সক্ষম করে এর অভ্যন্তরীণ কার্যপ্রণালী দেখতে পারেন।

Logback Configuration (Spring Boot Example):

<configuration>
    <logger name="com.fasterxml.jackson" level="DEBUG" />
</configuration>

আউটপুট:

DEBUG com.fasterxml.jackson.databind.deser.BeanDeserializerFactory - Deserializing property: "name"
DEBUG com.fasterxml.jackson.databind.deser.BeanDeserializerFactory - Deserialization failed for field: "age"

4. Unrecognized Properties হ্যান্ডল করা

JSON-এ অতিরিক্ত ফিল্ড পাওয়া গেলে UnrecognizedPropertyException ঘটে। এটি প্রতিরোধ করতে @JsonIgnoreProperties ব্যবহার করুন।

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    private String name;
    private int age;

    // Getters and Setters
}

বা Globally Configure করুন:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

5. Validate JSON Input

Jackson ব্যবহার করার আগে JSON-এর গঠন বৈধ কিনা তা যাচাই করা। এটি JsonNode এবং Tree Model ব্যবহার করে করা যায়।

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonValidationExample {
    public static void main(String[] args) {
        String invalidJson = "{ \"name\": \"John\", \"age\": \"invalid_number\" }";

        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readTree(invalidJson);

            if (!node.has("name") || !node.has("age")) {
                throw new IllegalArgumentException("Required fields are missing");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

6. Use Custom Deserializer for Better Debugging

কাস্টম Deserializer তৈরি করে আরো স্পষ্ট ডিবাগ বার্তা পাওয়া যায়।

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import java.io.IOException;

public class User {
    private String name;

    @JsonDeserialize(using = AgeDeserializer.class)
    private int age;

    // Getters and Setters
}

class AgeDeserializer extends JsonDeserializer<Integer> {
    @Override
    public Integer deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
        try {
            return Integer.parseInt(parser.getText());
        } catch (NumberFormatException e) {
            throw new IOException("Age must be a valid integer, but found: " + parser.getText());
        }
    }
}

7. Test with Invalid JSON Cases

API ডেভেলপমেন্টের সময় কিছু সাধারণ ত্রুটি পরীক্ষা করুন:

  1. Missing Fields: প্রয়োজনীয় ফিল্ড বাদ।
  2. Invalid Types: যেমন স্ট্রিং-এর পরিবর্তে সংখ্যা।
  3. Extra Fields: JSON-এ অতিরিক্ত ফিল্ড।
@Test
public void testInvalidJson() {
    String invalidJson = "{ \"name\": \"John\", \"age\": \"invalid_number\" }";

    Assertions.assertThrows(CustomJsonException.class, () -> {
        ObjectMapper mapper = new ObjectMapper();
        mapper.readValue(invalidJson, User.class);
    });
}

8. Use Global Exception Handler in Spring Boot

Spring Boot-এ @ControllerAdvice ব্যবহার করে Jackson Exception গ্লোবালি হ্যান্ডল করুন।

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(JsonMappingException.class)
    public ResponseEntity<String> handleJsonMappingException(JsonMappingException e) {
        return new ResponseEntity<>("JSON Mapping Error: " + e.getMessage(), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(JsonParseException.class)
    public ResponseEntity<String> handleJsonParseException(JsonParseException e) {
        return new ResponseEntity<>("JSON Parse Error: " + e.getMessage(), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGenericException(Exception e) {
        return new ResponseEntity<>("Unexpected Error: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

আউটপুট:

{
  "error": "JSON Mapping Error: Cannot deserialize value of type `int` from String \"invalid_number\""
}

Jackson Exception Logging এবং Debugging-এর জন্য:

  1. Logger ব্যবহার করুন: Exception Stack Trace এবং Contextual Message।
  2. Custom Exception তৈরি করুন: বিস্তারিত বার্তা এবং কারণ প্রদর্শনের জন্য।
  3. Debugging Logs সক্ষম করুন: Jackson এর অভ্যন্তরীণ কার্যপ্রণালী বুঝতে।
  4. Validation নিশ্চিত করুন: JSON ডেটা প্রসেস করার আগে validate করুন।
  5. Global Exception Handler: Spring Boot-এ Exception সঠিকভাবে হ্যান্ডল করুন।

এই পদ্ধতিগুলো ব্যবহার করে আপনি API-এর কার্যকারিতা এবং ত্রুটি সমাধান প্রক্রিয়া আরো দক্ষতার সাথে পরিচালনা করতে পারবেন।

Content added By
Promotion

Are you sure to start over?

Loading...