你应该试试 Jersey 的 ExceptionMapper:
首先,您的自定义例外:
public class UnauthorizedException extends RuntimeException {
public UnauthorizedException() {}
}
然后,您的实体,您要发回:
@XmlRootElement
public class ErrorMessage{
@XmlElement
private String message;
public ErrorMessage(String message){
this.message = message;
}
}
最后,魔术开始了:)
@Provider
public class UnauthorizedExceptionMapper implements ExceptionMapper<UnauthorizedException>{
@Override
public Response toResponse(UnauthorizedException exception) {
return Response.status(Response.Status.UNAUTHORIZED)
.entity(new ErrorMessage("Not Authorized"))
.build();
}
}
现在,当您返回一个 JSON-Entity
throw new UnauthorizedException();
问候