泽西自定义异常未被ExceptionMapper捕获

时间:2014-12-08 16:58:57

标签: exception parameters jersey jax-rs

我正在构建REST API并创建了一些自定义参数类型,这些参数类型在QueryParameters上应用了一些验证而不仅仅是。问题是我正在抛出一个" IllegalQueryArgumentException"但它并没有被自定义的ExceptionMapper捕获。

如果我从控制器方法中抛出异常,则会捕获异常。

我使自定义异常扩展WebApplicationException而不是RuntimeException

@Provider
public class CustomHandler implements ExceptionMapper<IllegalQueryArgumentException> {

    Override
    public Response toResponse(IllegalQueryArgumentException e) {
        return Response.accepted("HELLO").build();
    }
}

配置

<servlet>
    <servlet-name>rest</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.epaas.eshop.api.v1;com.epaas.eshop.api.v1.jersey;org.codehaus.jackson.jaxrs</param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>com.epaas.eshop.api.v1.jersey.CustomHandler</param-value>
    </init-param>

抽象参数

public abstract class AbstractQueryParameter<V> {

private final V value;
private final String originalParameter;

public AbstractQueryParameter(String param) throws InvalidQueryArgumentException {
        this.originalParameter = param;
        this.value = parse(param);
}

public V getValue() {
    return value;
}

public String getOriginalParameter() {
    return originalParameter;
}

@Override
public String toString() {
    return value.toString();
}

protected abstract V parse(String param) throws InvalidQueryArgumentException;

}

自定义参数类

public class IdParam extends AbstractQueryParameter<Long> {

public IdParam(String param) {
    super(param);
}

@Override
protected Long parse(String param) {
    try {
        Long id = Long.parseLong(param);
        if(id < 1) throw new Throwable("Id is under 1");
        return Long.parseLong(param);
    } catch (Throwable throwable) {
        throw new InvalidQueryArgumentException("parameter should be an integer", throwable);
    }
}
}

当Jersey尝试将String参数绑定到IdParam类型时,会自动调用parse方法。 路线方法..

@SuppressWarnings("unchecked")
@GET
public CollectionResource getAll(
        @Context UriInfo info,
        @QueryParam("expand") @DefaultValue("false") BooleanParam expand,
        @QueryParam("city") IdParam city,
        @QueryParam("account") IdParam account,
        @QueryParam("zipCode") ZipCodeParam zipCode,
        @QueryParam("limit") @DefaultValue(Pagination.DEFAULT_LIMIT) LimitParam limit,
        @QueryParam("offset") @DefaultValue(Pagination.DEFAULT_OFFSET) OffsetParam offset) {

0 个答案:

没有答案