如何在Spring中返回http响应

如何在Spring中返回http响应,spring,http,Spring,Http,我想用一个响应来替换http异常,也就是说,我使用我想返回的responseentity,例如409,如果没有通过名称找到用户,509,如果没有通过邮件找到,我可以在responseentity中确定错误号及其描述吗?如果是,你能举个例子吗 @RequestMapping(value = "/change", method = RequestMethod.POST) public void change(@RequestBody User user) throws Exception {

我想用一个响应来替换http异常,也就是说,我使用我想返回的responseentity,例如409,如果没有通过名称找到用户,509,如果没有通过邮件找到,我可以在responseentity中确定错误号及其描述吗?如果是,你能举个例子吗

@RequestMapping(value = "/change", method = RequestMethod.POST)
public void change(@RequestBody User user) throws Exception {
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    User userByUsername = userService.findUserByUsername(userDetails.getUsername());
    if (userByUsername == null) {
        throw new Exception("Пользователь не найден");
        //TODO: return ResponseEntity code 409 if userByusername not found
    }

    user.setId(userByUsername.getId());
    if (user.getPassword() == null) {
        user.setPassword(userByUsername.getPassword());
    }
    user.setRoles(userByUsername.getRoles());
    userService.save(user);
}

}

查看此链接,讨论相同的要求不清楚ErrorResponse类来自何处
public ResponseEntity<Object> change(@RequestBody User user) throws Exception {
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT, "not found user by username",409);
    User userByUsername = userService.findUserByUsername(userDetails.getUsername());
    if (userByUsername == null) {
        return new ResponseEntity<>(errorResponse, new HttpHeaders(), errorResponse.getStatus());
    }
    user.setId(userByUsername.getId());
    if (user.getPassword() == null) {
        user.setPassword(userByUsername.getPassword());
    }
    user.setRoles(userByUsername.getRoles());
    userService.save(user);
    return null;
}

public class ErrorResponse {

private HttpStatus status;
private String message;
private Integer errors;

public ErrorResponse(HttpStatus status, String message, Integer errors) {
    super();
    this.status = status;
    this.message = message;
    this.errors = errors;
}

public HttpStatus getStatus() {
    return status;
}