Reputation: 83
I would like my API to return errorMessage when the request lacks of required parameters. For example let's say there is a method:
@GET
@Path("/{foo}")
public Response doSth(@PathParam("foo") String foo, @NotNull @QueryParam("bar") String bar, @NotNull @QueryParam("baz") String baz)
where @NotNull
is from package javax.validation.constraints
.
I wrote an exception mapper which looks like this:
@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
}
but next.getPropertyPath().toString()
returns string in format method_name.arg_no
, f.e. fooBar.arg1 is null
I'd like to receive output fooBar.baz is null
or simply baz is null
.
My solution was to include -parameters
parameter for javac but to no avail.
Probably I could somehow achieve it with the use of filters:
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 (?)
}
}
}
The only problem with the above idea is that ExeptionMapper is executed first, then the filter is executed. Also I have no idea how could I possibly transfer errorMessage between ExceptionMapper and Filter. Maybe there is another way?
Upvotes: 3
Views: 1346
Reputation: 209004
You can inject ResourceInfo
into the exception mapper to get the resource method.
@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();
}
}
Upvotes: 2