我正在将 Apache Wink 与 JAX-RS 结合使用,并且正在努力抛出自定义异常以进行错误处理。我能够让某些东西足够有效地发送回带有状态代码的自定义 JSON 消息,但我希望能够将此自定义异常用于不止一种类型的响应(在本例中,Status .BAD_REQUEST
)。如何将状态代码注入(inject)到异常中,以便可以使用自定义错误消息抛出不止一种类型的状态?
JAX-RS 资源
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response memberRegistration(
JSONObject json,
@HeaderParam("Client-ID") String clientId,
@HeaderParam("Client-Secret") String clientSecret) throws WebApplicationException, Exception {
// Authenticate the user using the credentials provided
appAuth.checkClientId(clientId, clientSecret);
if (!"new".equals(json.get("type_of_membership"))) {
throw new WebApplicationException("Type of membership (new) is not correct for this route.");
}
return Response.ok(json, MediaType.APPLICATION_JSON).build();
}
自定义异常
public class WebApplicationException extends Exception implements Serializable
{
private static final long serialVersionUID = 1L;
public WebApplicationException() {
super();
}
public WebApplicationException(String msg) {
super(msg);
}
public WebApplicationException(String msg, Exception e) {
super(msg, e);
}
}
自定义异常处理程序/ExceptionMapper 实现
@Provider
public class WebApplicationExceptionHandler implements ExceptionMapper<WebApplicationException>
{
@Override
public Response toResponse(WebApplicationException exception)
{
JSONObject json = new JSONObject();
json.put("message", exception.getMessage());
return Response.status(Status.BAD_REQUEST).entity(json.toString()).build();
}
}
最佳答案
我不知道是否收到您的问题,但我可以建议向您的自定义异常添加一个实例变量来保存您想要的状态代码,您可以按如下方式执行操作:
public class WebApplicationException extends Exception implements Serializable
{
private static final long serialVersionUID = 1L;
private Response.Status status = Response.Status.BAD_REQUEST;
public WebApplicationException() {
super();
}
public WebApplicationException(String msg) {
super(msg);
}
public WebApplicationException(String msg, Exception e) {
super(msg, e);
}
public WebApplicationException(String msg, Response.Status status) {
super(msg);
this.status = status;
}
public WebApplicationException(String msg, Exception e, Response.Status status) {
super(msg, e);
this.status = status;
}
public Response.Status getStatus() {
return status;
}
}
那么你可以将“WebApplicationExceptionHandler”中的return语句修改为
return Response.status(exception.getStatus()).entity(json.toString()).build();
关于java - 带有状态代码的非 Jersey JAX-RS 自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37681204/