When in the controller of the springmvc project, the code is:
@Controller
@RequestMapping("/detail")
public class FileDetailController {
@RequestMapping("/add_detail")
@ResponseBody
public Object addDetailWithVersionId(@RequestParam(required=true)String versionId,
String description) {
if(hasVersion(versionId)) {
FileDetail fileDetail = new FileDetail();
fileDetail.setId(UUIDUtil.getUUID());
fileDetail.setDescription(description);
fileDetail.setVersionId(versionId);
// detailService.insert(fileDetail);
return JsonUtil.SUCCESS;
}
return JsonUtil.ERROR;
}
On my browser, I input http://localhost:8080/file_server/detail/add_detail and then get message: HTTP Status 400 - Required String parameter 'versionId' is not present. Oh the code @RequestParam(required=true)String versionId played a role in. But Is there a suitable method, return json to front-end in this case?
(OPTION 1) If you want to change return to frontend, you can implement custom org.springframework.boot.autoconfigure.web.ErrorController
For example with:
@RestController
public class MyErrorController extends AbstractErrorController {
private static final String PATH = "/error";
@Autowired
public MyErrorController(ErrorAttributes errorAttributes) {
super(errorAttributes);
}
@RequestMapping(value = PATH)
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request, false);
HttpStatus status = getStatus(request);
return new ResponseEntity<Map<String, Object>>(body, status);
}
@Override
public String getErrorPath() {
return PATH;
}
}
you will now always get something like this json:
{
"timestamp": 1462600073772,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.MissingServletRequestParameterException",
"message": "Required String parameter 'versionId' is not present",
"path": "/add_detail"
}
can customize it whatever you like if you want to. Just change error method in controller.
(OPTION 2) Use custom @ExceptionHandler in your controller. Can read this for more info https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
Just add something like this in your FileDetailController
@Autowired
private ErrorAttributes errorAttributes;
@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<Map<String, Object>> handle(HttpServletRequest request, Exception exception) {
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
Map body = this.errorAttributes.getErrorAttributes(requestAttributes,false);
return new ResponseEntity<Map<String, Object>>(body, HttpStatus.BAD_REQUEST);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With