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

时间:2018-06-11 16:33:53

标签: java java-ee jaxb jersey

我希望我的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 is null

我希望收到输出fooBar.baz is null或只是baz is 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。也许有另一种方式?

1 个答案:

答案 0 :(得分:2)

您可以将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();
    }
}