@POST
@Path("/login")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response login(Member member) {
Response.ResponseBuilder builder = null;
try {
LogMsg.info("Login User " + member.getUsername() + " Password : "+ member.getPassword());
member.setPassword(member.getPassword());
repository.validateLogin(member);
builder = Response.ok();
} catch (ConstraintViolationException ce) {
ErrorMessages errorMessage = new ErrorMessages(ce.getMessage(), 409, "username is wrong");
LogMsg.error("ConstraintViolationException " + ce.getMessage());
builder = Response.status(409)
.entity(errorMessage);
} catch (ValidationException e) {
Map<String, String> responseObj = new HashMap<String, String>();
responseObj.put("username", "Invalid Username");
ErrorMessages errorMessage = new ErrorMessages(e.getMessage(), 404, "password is wrong");
LogMsg.error("ValidationException " + e.getMessage());
builder = Response.status(404)
.entity(errorMessage);
} catch (Exception e) {
Map<String, String> responseObj = new HashMap<String, String>();
responseObj.put("error", e.getMessage());
LogMsg.error(e.getMessage());
builder = Response.status(Response.Status.BAD_REQUEST).entity(
responseObj);
}
return builder.build();
}
注意:如果用户名和密码正确,我将200k发送给客户端。 1)如果用户名和密码错误,我们提出异常代码我需要发送给客户端的异常。 任何身体都可以帮助我。
谢谢, 马丹
答案 0 :(得分:0)
是您可以使用例外代码发送响应。 你的代码是好的只是你必须从catch块返回响应。 我试图修改你的代码。
@POST
@Path("/login")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response login(Member member) {
Response.ResponseBuilder builder = null;
try {
LogMsg.info("Login User " + member.getUsername() + " Password : "+ member.getPassword());
member.setPassword(member.getPassword());
repository.validateLogin(member);
builder = Response.ok();
} catch (ConstraintViolationException ce) {
ErrorMessages errorMessage = new ErrorMessages(ce.getMessage(), 409, "username is wrong");
LogMsg.error("ConstraintViolationException " + ce.getMessage());
return Response.status(409).entity(errorMessage).type(MediaType.APPLICATION_JSON).build();
} catch (ValidationException e) {
Map<String, String> responseObj = new HashMap<String, String>();
responseObj.put("username", "Invalid Username");
ErrorMessages errorMessage = new ErrorMessages(e.getMessage(), 404, "password is wrong");
LogMsg.error("ValidationException " + e.getMessage());
return Response.status(404).entity(errorMessage).type(MediaType.APPLICATION_JSON).build();
} catch (Exception e) {
Map<String, String> responseObj = new HashMap<String, String>();
responseObj.put("error", e.getMessage());
LogMsg.error(e.getMessage());
return Response.status(400).entity(errorMessage).type(MediaType.APPLICATION_JSON).build();
}
return builder.build();
}