泽西错误处理+泛型响应对象

时间:2016-06-05 03:59:47

标签: java generics exception-handling jersey

我正在用球衣打造restapi。我的示例休息GET方法工作正常。 如果restapi方法中有任何异常,我的扩展javax.ws.rs.ext.ExceptionMapper的类会捕获异常,将其映射到 RestapiResponse 对象并将其发送回客户端。

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/hello/{key}")
public Orange sayHello(@PathParam("key") String key) {
   ...
}

我的RestapiResponse课程必须是这样的:

class RestapiResponse {
    private int httpStatus;
    private int errorCode;
    private String message;
    private String link;
    private String description;
    private String errorStackTrace;
    private Class<T> response; <-- holds the response object of rest call

    // getters/setters are here

    // produces a new instance of class and set the response object 
    public static RestapiResponse getInstance(T response, Class<T> type) {
        this.response = response;
    }
}

我需要这样的通用restapi调用者:

class RestapiCaller {
    public static RestapiResponse get(String uri, Class<T> type) {
        // jersey rest client call
        Client client = ClientBuilder.newClient();
        ...
        Response response = builder.get();

        if (response.getStatus() == 200) {
            return RestapiResponse.getInstance(response.readEntity(type), type);
        else
            return response.readEntity(RestapiResponse.class);
    }
}

用法:

RestapiResponse r = RestapiCaller.get("host:port/.../api/...", Orange.class)
if (r.getHttpStatus() == 200) {
    Orange o = r.getResponse();
}

RestapiResponse r = RestapiCaller.get("host:port/.../api/...", Car.class)
if (r.getHttpStatus() == 200) {
    Car c = r.getResponse();
}

我想请求帮助来实现RestapiResponse.getInstance()和RestapiCaller.get()方法。

0 个答案:

没有答案