Home > Software design >  ExceptionHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReada
ExceptionHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReada

Time:10-29

If request body json is not provided, How to handle customized exception in which ResponseEntity of pojo or bean type in spring boot.

I'm trying fetch the response as JSON from external API by providing the request body as JSON. I'm able to do that as follows. But if request body JSON is not provided then I need to give response as JSON like { msg : "Request Body is needed"}

@PostMapping(value="/postdata",produces = MediaType.APPLICATION_JSON_VALUE)
private ResponseEntity<DataResponse> postData(@RequestBody DataRequest json) throws JsonProcessingException {

    String uri = "http://...."; //External API
    ResponseEntity<String> response = null;
    DataResponse data = null;
    
    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers  = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    ObjectMapper obj = new ObjectMapper();

    HttpEntity<String> entity = new HttpEntity<String>(obj.writeValueAsString(json),headers);
        
    response = restTemplate.postForEntity(uri, entity, String.class);
    String result = response.getBody().toString();
    
    JSONObject jobj = new JSONObject(result);
    System.out.println("jobj ==="  jobj.getJSONObject("data").toString());
    
    String data = jobj.getJSONObject("data").toString();
     data = obj.readValue(jobj.toString(), DataResponse.class);
    
    return ResponseEntity.status(HttpStatus.OK).body(segment);
}

// ...

if( user == null ) {
    throw new userdefinedException("RequestBody is Required");
}

I tried use like the above but I'm getting no response empty in console

How to handle these type of exceptions.

Thanks in Advance

CodePudding user response:

In Controller, API method added this condition

// for null check of object

if( user == null ) {  
    throw new UserNotFoundException("RequestBody is Missing");
}

@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
public class UserNotFoundException extends RuntimeException{
    private static final long serialVersionUID = 1L;

    public UserNotFoundException(String message) {
        super(message);
    } 
}


@ControllerAdvice
@RestController
public class DefaultExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(UserNotFoundException.class)
    public final ResponseEntity<Object> handleRequestBodyNotFound(UserNotFoundException ex, WebRequest request) {

        ErrorMessage exceptionResponse = new ErrorMessage(new Date(), ex.getMessage(),request.getDescription(false));
        //exceptionResponse.setTimestamp(LocalDateTime.now());
        return new ResponseEntity<Object>(exceptionResponse,new HttpHeaders(), HttpStatus.UNPROCESSABLE_ENTITY.value());

    }
}
  • Related