How to handle “org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error” in Spring?

We Are Going To Discuss About How to handle “org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error” in Spring?. So lets Start this Java Article.

How to handle “org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error” in Spring?

  1. How to handle “org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error” in Spring?

    This should work but Spring is not meant to handle error before the HTTP request can be deserialized correctly. You can write rules on request data after deserialization using annotation on your DTO class's fields like @NotNull, @NotEmpty, @Positive, …

  2. “org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error” in Spring

    This should work but Spring is not meant to handle error before the HTTP request can be deserialized correctly. You can write rules on request data after deserialization using annotation on your DTO class's fields like @NotNull, @NotEmpty, @Positive, …

Solution 1

This should work but Spring is not meant to handle error before the HTTP request can be deserialized correctly. You can write rules on request data after deserialization using annotation on your DTO class’s fields like @NotNull, @NotEmpty, @Positive, …

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ErrorController {
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<String> handleException(HttpMessageNotReadableException exception, HttpServletRequest request) {
        return new ResponseEntity("You gave an incorrect value for ....", HttpStatus.BAD_REQUEST);
    }
}

Original Author Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment