harish
harish

Reputation: 23

Spring boot response body is showing empty in PostMan

I am using @Valid annotation to validate some of my model properties. It is working as expected, if any data is not provided as per the expectation it is throwing back 400 Bad Request error. But the response body is always coming as empty.

My Controller Class

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.bnpp.leavemanagement.exception.DepartmentNotFoundException;
import com.bnpp.leavemanagement.exception.EmployeeAlreadyExistsException;
import com.bnpp.leavemanagement.exception.EmployeeNotFoundException;
import com.bnpp.leavemanagement.model.EmployeeModel;
import com.bnpp.leavemanagement.service.EmployeeService;

@RestController
@Validated
@RequestMapping("/employee")
public class EmployeeController 
{
    @Autowired
    EmployeeService empService;
    
    
    @PostMapping("/create")
    public ResponseEntity<EmployeeModel> createEmployee(@RequestBody @Valid EmployeeModel empNew) throws  EmployeeAlreadyExistsException, DepartmentNotFoundException, EmployeeNotFoundException
    {
        EmployeeModel resEmp = empService.addEmployee(empNew);
        return new ResponseEntity( resEmp, HttpStatus.CREATED);
    }

Model Class Property

  @JsonProperty("firstName")
  @NotEmpty(message = "FirstName cannot be empty")
  private String firstName = null;

application.properties

spring.datasource.url=jdbc:h2:mem:leavemgmt
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true

server.port=8443

server.ssl.key-alias=leavemanagement
server.ssl.key-store=classpath:leavemanagement.jks
server.ssl.key-store-type=JKS
server.ssl.key-store-password=password

server.error.include-message=always
server.error.include-binding-errors=always
server.error.include-exception=true
server.error.include-stacktrace=always

PostMan Response

Please help me on what to be done to get the response body in Postman on any validation failure.

Upvotes: 1

Views: 3277

Answers (1)

user404
user404

Reputation: 2028

You need to add your errors in your response using BindingResult like this in your controller:

 public ResponseEntity<EmployeeModel> createEmployee(@Valid @RequestBody EmployeeModel empNew,BindingResult bindingResult)
{
  if(bindingResult.hasErrors())
   {
     for(FieldError fieldError : bindingResult.getFieldErrors()) {
            //you can define your ErrorMOdel dto here and add  
          //fieldError properties then add the whole errorList in 
          //your response.
         //Finally, return the response from here
        }
   }

  //if there is no errors in your request: execute this part:
   EmployeeModel resEmp = empService.addEmployee(empNew);
        return new ResponseEntity( resEmp, HttpStatus.CREATED);

}

Update according to your need:
You can define your EmployeeModel in this way:

public class EmployeeModel<T> implements Serializable
{
  //your previously defined entities here
     private List<T> errorList;  //this is new one to show errors

    //constructors, setters, getters
}

Now, when you get error, replace the previous code with this:

if(bindingResult.hasErrors())
       {
         EmployeeModel response= new EmployeeModel();
         for(FieldError fieldError : bindingResult.getFieldErrors()) 
            {
               response.setErrorList(bindingResult.getFieldErrors());
            }
           return new ResponseEntity( response, 
            HttpStatus.BAD_REQUEST);
       }

Further improvisation you can carry on:
You can add another field as status in your EmpoloyeeModel, status will be set as success when there is no error, otherwise, set to error i.e employeeModel.setStatus("success") or.setStatus("error") depending on the situation Better, write a generic Response class to hold all type of response like this:

@Data
@NoArgsConstructor
public class ServiceResponse<T> implements Serializable {
private HttpStatus status; //OK_Failure
private StatusCode statusCode; //code
private T body;
private List<T> errorList;
}

Let me know if you face any problem regarding this.

Upvotes: 1

Related Questions