嗨,这是一个糟糕的设计?如果一切按计划进行,我想返回个人资料。如果不是,我想返回我的自定义错误消息。
这可以吗?
@RequestMapping(value = "/{userId}", method = RequestMethod.PUT)
public @ResponseBody
Object saveUser(@PathVariable Long userId, ModelMap data, @Valid Profile profile, BindingResult bindingResult, HttpServletResponse response) {
if (bindingResult.hasErrors()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return ValidationUtil.createValidationErrors(bindingResult);
}
profileService.save(profile);
return profile;
}
答案 0 :(得分:1)
你应该使用 @ExceptionHandler(Exception.class)和@ResponseStatus Annotation
实施例
@ExceptionHandler (Exception.class)
@RequestMapping(value = "/{userId}", method = RequestMethod.PUT)
public @ResponseBody
Profile saveUser(@PathVariable Long userId, ModelMap data, @Valid Profile profile, BindingResult bindingResult, HttpServletResponse response) {
if (bindingResult.hasErrors()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
throw new Exception("message");
if(ValidationUtil.createValidationErrors(bindingResult)) {
throw new Exception("message");
}
}
profileService.save(profile);
return profile;
}
有关详细信息,请参阅
http://jnb.ociweb.com/jnb/jnbNov2010.html
http://www.stormpath.com/blog/spring-mvc-rest-exception-handling-best-practices-part-1
http://blog.cuttleworks.com/2011/12/spring-restful-controllers-and-error-handling/
答案 1 :(得分:0)
如果您需要访问配置文件对象,我建议您将其添加到会话或请求上下文中。然后,您可以从saveUser方法返回一个字符串(如果您愿意,还可以返回ModelAndView对象),并且该对象仍可用于以后的请求。