春季有休息服务:
@RestController
public class UserController {
@Autowired
private UserService service;
@RequestMapping(value = "/users", method = RequestMethod.POST)
public Users add(@RequestBody Users users,
@RequestParam(value = "id", required = false) String id) {
return service.add(id, users.getUsers());
}
@RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
public @ResponseBody Users findById(@PathVariable(value = "id") String id) throws Exception {
return service.find(id);
}
}
使用 xml 和 jaxb 与客户端进行交换。用户实体如下所示:
@XmlRootElement(name = "Users")
@NoArgsConstructor
@AllArgsConstructor
@XmlAccessorType(XmlAccessType.FIELD)
@Getter
@Setter
public class Users {
@XmlElement(name = "users")
private List<User> Users;
@XmlElement(name="UserError")
private UserError error;
public void appendUsers(Users Users){
if (Users == null) return;
if (Users.getError() != null){
this.error = Users.getError();
}
if ( Users.getUsers() != null) {
if (this.Users == null){
this.Users = new ArrayList<>();
}
this.Users.addAll(Users.getUsers());
}
}
}
也就是说,实际上,这是两个字段,其中一个存储用户列表,另一个 - 如果发生错误则错误。
在service.add执行过程中,可能会出现错误,例如数据库不可用,该方法会返回异常。额头的解决方法是把所有的服务调用都包装在一个try catch中,如果出现异常,在Users.error中记录这个错误。
有没有更优雅的解决方案?
当然有。为了捕获错误,比如 UserController 中的 UserNotFoundException,您需要添加一个带有 @ExceptionHandler 注释的方法:
为了从所有 RestController 中捕获错误,例如 IllegalArgumentException,您需要使用 @ControllerAdvice 注释声明一个类: