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

Java 验证失败时包含参数名称的自定义错误消息,java,jakarta-ee,jaxb,jersey,Java,Jakarta 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 我编写了一个异常映

我希望我的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
  }
上述想法的唯一问题是先执行exoptionMapper,然后执行过滤器。此外,我也不知道如何在ExceptionMapper和Filter之间传输errorMessage。也许还有另一种方法?

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

@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();
    }
}
@Provider
公共类映射器扩展了ExceptionMapper{
@上下文
私有资源信息资源信息;
@凌驾
公众对响应的响应(ConstraintViolationException ex){
方法resourceMethod=resourceInfo.getResourceMethod();
参数[]参数=resourceMethod.getParameters();
}
}
@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();
    }
}