验证失败时包含参数名称的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 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 (?)
}
}
}
上述想法的唯一问题是先执行exoptionMapper,然后执行过滤器。此外,我也不知道如何在ExceptionMapper和Filter之间传输errorMessage。也许还有别的办法
# 1 楼答案
可以将^{} 注入异常映射器以获取资源方法