简体   繁体   中英

Apache CXF - Handle missing path parameters in an operation

I am using apache cxf for Jax-rs implementation in my project. I have a service defined with the following address: http://ip:port/myservice/ {operation}

consider an operation for this server defined as below

@Override
@GET
@Path("operation1/{x}/{y}")
@Produces("application/xml")
public String operation1(@PathParam("x") final String x, @PathParam("y") final String y) {
    return null;
}

In the scenario where the requester makes a request with some operation name that is not defined in myservice, it will return 404 which is expected behavior. But i am getting the same 404 in cases where operation name is correctly requested but path parameters are not. I would like to create a proper error if any of {x} or {y} path param is missing in a request. But i cannot find a graceful way where i can handle exceptions as per the operations. CXF never maps to the operation in such cases.

I have this exception mapper:

public class ClientExceptionMapper implements ExceptionMapper<ClientErrorException> {

@Override
public Response toResponse(final ClientErrorException exception) {
    return Response.status(Response.Status.FORBIDDEN).entity("Invalid request").build();

}

}

Which will handle all error cases but it doesn't provide any information as to what URL was requested in the exception. Is there a way where i can handle exceptions differently for different operations in cases when path parameters are not defined ? For eg: I would like to handle following request with some custom logic defined for operation1 only. http://ip:port/myservice/operation1/20

I see two solutions for your case.
1) Move your path params to query param. @QueryParam
2) Create a filter and map it to url operation1/*

While finding solution for my scenario where i need to validate path parameters, i found this link which suggests a nice workaround for my problem. Although its just a hack and might not be a good idea to implement in existing code, you can consider it if you need to play around with path parameters within your respective operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM