java – 验证失败时包含参数名称的自定义错误消息

我希望我的API在请求缺少必需参数时返回errorMessage.例如,假设有一种方法:

@GET
@Path("/{foo}")
public Response doSth(@PathParam("foo") String foo, @NotNull @QueryParam("bar") String bar, @NotNull @QueryParam("baz") String baz)

其中@NotNull来自包javax.validation.constraints.

我写了一个异常映射器,如下所示:

@Provider
public class Mapper extends ExceptionMapper<ConstraintViolationException> {

  @Override
  public Response toResponse(ConstraintViolationException) {
    Iterator<ConstraintViolation<?>> it= exception.getConstraintViolations().iterator();
    StringBuilder sb = new StringBuilder();
    while(it.hasNext()) {
      ConstraintViolation<?> next = it.next();
      sb.append(next.getPropertyPath().toString()).append(" is null");
    }
    // create errorMessage entity and return it with apropriate status
  }

但是next.getPropertyPath().toString()以method_name.arg_no,f.e.格式返回字符串. fooBar.arg1为null

我想收到输出fooBar.baz为null或只是baz为null.

我的解决方案是为javac包含-parameters参数,但无济于事.

也许我可以通过使用过滤器以某种方式实现它:

public class Filter implements ContainerResponseFilter {

@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {

    UriInfo uriInfo = requestContext.getUriInfo();
    UriRoutingContext routingContext = (UriRoutingContext) uriInfo;

    Throwable mappedThrowable = routingContext.getMappedThrowable();

    if (mappedThrowable != null) {
        Method resourceMethod = routingContext.getResourceMethod();
        Parameter[] parameters = resourceMethod.getParameters();

      // somehow transfer these parameters to exceptionMapper (?)
    }
  }
}

上述想法的唯一问题是首先执行ExeptionMapper,然后执行过滤器.另外我不知道怎么可能在ExceptionMapper和Filter之间传递errorMessage.也许有另一种方式?

解决方法:

您可以将ResourceInfo注入异常映射器以获取资源方法.

@Provider
public class Mapper extends ExceptionMapper<ConstraintViolationException> {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public Response toResponse(ConstraintViolationException ex) {
        Method resourceMethod = resourceInfo.getResourceMethod();
        Parameter[] parameters = resourceMethod.getParameters();
    }
}
上一篇:java – 文件上传以及Jersey restful web服务中的其他对象


下一篇:android – Java jersey RESTful webservice请求