krish
krish

Reputation: 369

How to POST REST correct error status code using Spring Exception handling

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

Upvotes: 0

Views: 1898

Answers (3)

Saravana
Saravana

Reputation: 12817

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

}

Upvotes: 0

Luke Russert
Luke Russert

Reputation: 31

In your catch statement, try to set the status through

response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );

Source

Upvotes: 1

Master Slave
Master Slave

Reputation: 28569

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);
 }

Upvotes: 1

Related Questions