Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS exception handling

Tags:

rest

jax-rs

cxf

I'm relatively new to REST services in Java. I've created one and everything works fine except error handling. If I make a request with incorrectly formed JSON in it, Jackson JSON processor throws an exception which I unable to catch and I get error 500 in client. Exception follows:

javax.ws.rs.InternalServerErrorException: org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.HashSet out of VALUE_STRING token

I have no idea how to handle exceptions raised outside my code. Google suggests using Exception Mappers or Phase Inteceptors. Though I could miss something in search results. What is the proper way to handle such situations? Please, advise something. I'm stuck with this problem...

like image 724
Aleksandr Kravets Avatar asked Jun 14 '13 13:06

Aleksandr Kravets


People also ask

How do you handle exceptions in JAX-RS?

Thrown exceptions are handled by the JAX-RS runtime if you have registered an exception mapper. Exception mappers can convert an exception to an HTTP response. If the thrown exception is not handled by a mapper, it is propagated and handled by the container (i.e., servlet) JAX-RS is running within.

What is the purpose of using JAX-RS?

JAX-RS is a Java programming language API designed to make it easy to develop applications that use the REST architecture. The JAX-RS API uses Java programming language annotations to simplify the development of RESTful web services.

What are the JAX-RS implementations?

JAX-RS is nothing more than a specification, a set of interfaces and annotations offered by Java EE. And then, of course, we have the implementations; some of the more well known are RESTEasy and Jersey.


1 Answers

A JAX-RS ExceptionMapper should do the job. Just add a class like below to your code and if you have the exception type right, then you should get the hook to customize the handling.

@Provider
public class MyExceptionMapper implements ExceptionMapper<MyException> {

    @Override
    public Response toResponse(MyException ex) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

}
like image 56
TheArchitect Avatar answered Sep 24 '22 12:09

TheArchitect