Spring如何返回http响应

时间:2019-02-01 11:10:30

标签: spring http

我想用响应替换http异常,也就是说,我使用responseentity我想返回例如409(如果找不到用户名)和509(如果找不到邮件),我可以确定错误号及其在responseEntity中的描述?如果可以,可以举个例子吗?

await

1 个答案:

答案 0 :(得分:-1)

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;
}

}