What is the correct way to handle a bad parameter in a RESTful service? I have an endpoint right now that returns 400 if the wrong data type is sent.
@ResponseBody @RequestMapping(produces = "application/json", method = RequestMethod.GET, value="/v1/test") public MyResponse getSomething(@RequestParam BigDecimal bd) { MyResponse r = new MyResponse(); r.setBd(bd); return r; }
It would be very nice if the end user passed, say, String instead of BigDecimal, that the response would return json with the response code, status and everything else that I want it to contain, not just 400. Is there a way to do this?
Update. My initial thought was to wrap each parameter and then check if it matches the correct type in this wrapper class. It seems a little silly. Isn't there a validator that I could just add to the classpath that recognizes something like this?
In addition, there is a way to handle this quite easily with a Bean type that I could create myself, but what about standard types like BigDecimal?
UPDATE-2: This update is responsible for the response using @ExceptionHandler.
TestController.java
import java.math.BigDecimal; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/") public class TestController {
TestUnitTest.java
public class TestUnitTest { protected MockMvc mockMvc; @Autowired protected WebApplicationContext wac; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test public void test() throws Exception { String url = "/v1/test?bd=a123.00"; log.info("Testing Endpoint::: " + url); MvcResult result = mockMvc.perform(get(url)) .andExpect(status().isOk()) .andReturn(); log.info("RESPONSE::: " + result.getResponse().getContentAsString()); } }
Myresponse.java
import java.math.BigDecimal; public class MyResponse { private BigDecimal bd; public BigDecimal getBd() { return bd; } public void setBd(BigDecimal bd) { this.bd = bd; } }
MyErrorResponse.java
public class MyErrorResponse { private Exception exception; public Exception getException() { return exception; } public void setEexception(Exception e) { this.exception = e; } }