0

I'm trying to handle missing json data in a POST request. My controller class

@Controller
@RequestMapping("/testMetrics")

public class TestMetricsEndPoint extends StatusEndpointHandler implements RestEndPoint<TestMetrics,String> {

@Autowired
private ObjectMapper mapper;

@Autowired
private TestMetricsService testMetricsService;

@Override
public Status get(String id) {
    // TODO Auto-generated method stub
    return null;
}


@Override
@RequestMapping(method = RequestMethod.POST,consumes = "application/json", produces = "application/json")
public @ResponseBody Status create(@RequestBody TestMetrics core, BindingResult bindingResult) {
    try {
    if(bindingResult.hasErrors()){
        throw new InvalidRequestException("Add failed, Please try again ", bindingResult);
    }
    if((core.getGroupName()==""||core.getGroupName()==null)&&(core.getTestName()==null||core.getTestName()=="")){

            throw new MissingParametersException(HttpStatus.BAD_REQUEST.value(),"Please provide all necessary parameters");
        } 
    TestMetrics dataObject = testMetricsService.create(core);
    return response(HttpStatus.CREATED.value(),dataObject);
    }catch (MissingParametersException e) {
        return             response(HttpStatus.BAD_REQUEST.value(),e.getLocalizedMessage());
    }

}

Extended class:

public class StatusEndpointHandler {


public Status response(Integer statusCode,Object data){
    Status status = new Status();
    status.setData(data);
    status.setStatus(statusCode);



    return status;
}

}

Implemented interface:

 public interface RestEndPoint<T extends SynRestBaseJSON, ID extends    Serializable> {

Status get(ID id);

Status create(T entity, BindingResult bindingResult);}

Result: enter image description here

Please look at the highlighted part So, when i tried to test the result through POSTMAN, i'm getting status as 200 OK. I have no idea hot to solve it. please help me with this situation. How to get the correct status code.?

Master Slave
  • 27,771
  • 4
  • 57
  • 55
krish
  • 349
  • 3
  • 17

3 Answers3

1

You should change your return type from @ResponseBody to ResponseEntity which will allow you to manipulate headers, therefor set the status, this is a snippet from the docs

 @RequestMapping("/handle")
 public ResponseEntity<String> handle() {
   URI location = ...;
   HttpHeaders responseHeaders = new HttpHeaders();
   responseHeaders.setLocation(location);
   responseHeaders.set("MyResponseHeader", "MyValue");
   return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
 }
Master Slave
  • 27,771
  • 4
  • 57
  • 55
  • Sorry, I'm not clear about what you said. I understood that i need to use @ResponseEntity. But, i did not get how to use it. – krish Jul 15 '16 at 05:03
  • I nearly hinted it as a right way to go. You should find plenty of resources to understand why, and how to use it. Basically, its the built-in class that is logic equivalent to your `StatusEndpointHandler` – Master Slave Jul 15 '16 at 05:05
1

In your catch statement, try to set the status through

response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );

Source

Community
  • 1
  • 1
0

The problem is with your code handing the string comparison, to compare strings you have to use equals, from Postman also you are passing empty testName and groupName

    if ((core.getGroupName() == "" || core.getGroupName() == null) && (core.getTestName() == null || core.getTestName() == "")) {
    }

so change your code to below

    if ((core.getGroupName() == null || core.getGroupName().trim().isEmpty()) && (core.getTestName() == null || core.getTestName().trim().isEmpty())) {

    } 

also write an ExceptionHandler for this

@ExceptionHandler({ MissingParametersException.class })
public ModelAndView handleException(ServiceException ex, HttpServletResponse response) {
    response.setStatus(HttpStatus.BAD_REQUEST.value());
    ModelMap model = new ModelMap();
    model.addAttribute("message", ex.getMessage());
    return new ModelAndView("error", model);
}

You can also define validation constrains in entity class using validation api, in this case you need to add @Valid to the request model object

@Entity
class TestMetrics {

    @Id
    Long id;

    @NotNull
    @NotEmpty
    @Column
    String groupName;

    @NotNull
    @NotEmpty
    @Column
    String testName;

    // Getters and Setters

}
Saravana
  • 12,647
  • 2
  • 39
  • 57