Java Rest,如何设置和显示自定义错误消息

时间:2014-03-06 14:47:05

标签: java javascript jersey

当登录因帐户被阻止而失败时,我想显示在后端设置的自定义消息。但是我无法在响应体中访问它,即使它设置正确也不能确定。

@POST
@Path(/login)
public Token logon() {
    ...

    String errorMsg = "This account is blocked please contact to Admin"
    throw new NotAuthorizedException(errorMsg);
}

当我收到我想要的错误消息时,在javascript方面:

if (rejection.status === 401) {
    //rejection can be because of blocked account or invalid password,
    //they will both return 401, but need to have different messages 

    $scope.message ="Show the error msg that I get from backend" ;
}

此处返回的拒绝对象包括config,data,status和headers对象。

但是我无法看到我在后端设置的消息。

1 个答案:

答案 0 :(得分:0)

您可以在创建NotAuthorizedException而不是仅显示消息时传递响应:

@POST
@Path(/login)
public Token logon() {
  ...

  String errorMsg = "This account is blocked please contact to Admin"
  throw new NotAuthorizedException(Response.status(Response.Status.UNAUTHORIZED).entity(errorMsg).build())
}

这应该在响应正文中返回您的错误消息