开发者

JAX-RS exception mapper does not handle the exception that is thrown when doing parameter conversion?

I created my own class with a fromString method which I believe JAXB will use to convert the parameter value string to my object. However, inside this fromString meth开发者_如何学编程od, I have a try catch block which bubbles up the exception. Like the following.

public class Animal{
    public static Animal fromString(final String input){ 

        try{ 
            ... 
        }catch(IllegalArgumentException ae){ 
            throw new CannotConvertAnimalException(); //this is my custom exception 
        } 
    }
}

And then I have a mapper for CannotConvertAnimalException like the following:

@Component
@Provider
public class CannotConvertAnimalExceptionHandler implements ExceptionMapper<CannotConvertAnimalException>

The thing is that in my resource method. I use the data type Animal

@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response showAnimalInfo(Animal animal){....}

It turns out that when the parameter string that is to be converted to Animal throws the CannotConvertAnimalException my custome exception mapper does not handle it. It goes on to throw ParamException.QueryParamException instead and gives it to my QueryParamException handler to handle the response.

Do you guys have any idea how to make it so that when the conversion goes bad, and when the CannotConvertAnimalException gets thrown, the correct mapper handles it?


Ok found the answer to this. It turns out that whatever exception you throw when trying to convert from string to object will be wrapped inside QueryParamException and thus will be handled by QueryParamException ExceptionMapper (if you have one). One way to get around this is to actually identify what exception is wrapped by QueryParamException and use some kind of Map to match the cause of the QueryParamException to the correct handler

Map<Exception, ExceptionMapper> mapper;

and

catch(Exception e){
    exMapper = mapper.get(exception.getCause);
}

of course you would need to load up yor map with the right exception and its mapper. I do this by having spring injects a map to this variable.


Try to use different JAX-RS framework. (Actually which framework do you use?)
I think in Wink your scenario will work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜