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

Custom error message containing parameter names when validation fails

当请求缺少必需的参数时,我希望我的 API 到 return 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() return 的字符串格式为 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,然后才执行了filter。我也不知道我怎么可能在 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();
    }
}