tehoo
tehoo

Reputation: 83

No serializer found Problem returning ResponseEntity including exception

Im making RESTful API for practice. I want to valid check request body and made ExceptionHandler.class like below.

  @Override
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request){

    List<String> errorList = ex
            .getBindingResult()
            .getFieldErrors()
            .stream()
            .map(DefaultMessageSourceResolvable::getDefaultMessage)
            .collect(Collectors.toList());

    ApiResponse apiResponse=new ApiResponse(HttpStatus.BAD_REQUEST, ex.getMessage(), errorList, ex);

    return new ResponseEntity<>(
            apiResponse, HttpStatus.BAD_REQUEST
            );
    }

I made ApiResponse.class for response body in ResponseEntity<>.

@Data
@Slf4j
public class ApiResponse{

    public HttpStatus status;
    public String msg;
    public List<String> err;
    public Exception ex;

    public ApiResponse(HttpStatus status, String msg, List<String> err, Exception ex){
        this.status=status;
        this.msg=msg;
        this.err=err;
        this.ex=ex;    
        }
}

but when MethodArgumentNotValidException happen, I got error like below...

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.springframework.validation.DefaultMessageCodesResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.practice.skillup.restfulapi.dto.ApiResponse["ex"]-

what is the reason and how can I resolve it. (I'm just a web develop beginner it would be very thankful to explain easily)

Upvotes: 0

Views: 3002

Answers (1)

user10260739
user10260739

Reputation:

This problem comes because entities are loaded lazily whereas the serialization process is performed before entities get loaded fully. Jackson tries to serialize the nested object but it fails as it finds JavassistLazyInitializer instead of the normal object.

As per your stack trace, You can suppress this error by adding the following configuration to your application.properties file:-

spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false

This will only hide the error but won't solve the issue. To solve the issue you can use the add-on module for Jackson which handles Hibernate lazy-loading. See more here:- Jackson-datatype-hibernate, how to configure Jackson-datatype-hibernate.

Upvotes: 4

Related Questions