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.?

3 Answers 3

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);
 }
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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
1

In your catch statement, try to set the status through

response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );

Source

Comments

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

}

4 Comments

have you entered testName and groupName ? it should not be empty or null as per the validation logic
Yes. I entered bot of them
could you post testName and groupName values inside the method create
updated code with exception handler, have a look at it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.