简体   繁体   中英

JAX-RS jersey ExceptionMapper: How to know the method who threw the exception

Im using JAX-RS jersey ExceptionMapper, and I'm wondering if there is a way to know inside the method toResponse(), which method (from the API) threw the exception.

Example (dummy code)

@javax.ws.rs.Path(“/bookstore/books/{bookID}”)
public class Book {
    @javax.ws.rs.GET
    public String informationMethod(String user) {
        ...
            throw new Exception("Error");
        ....    
    }    
}



@Provider
public class SomeMapper implements ExceptionMapper<Exception> {
    @Override
    public Response toResponse(Exception ex) {

        //a way to get the method name that threw the exception. 
        //In the above example is: informationMethod.
        String methodName = //informationMethod

        return Response.status(500).entity(ex.getMessage()).type("text/plain")
                .build();
    }
}

You can provide some information from context to your ExcpetionMapper .

package your.rest.pckg;

import java.lang.reflect.Method;
import java.net.URI;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Path;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class SomeMapper
                implements ExceptionMapper<Exception>
{

    @Context private HttpServletRequest request;

    @Context private HttpServletResponse response;

    @Context private ResourceInfo resourceInfo;

    @Context private UriInfo uriInfo;

    @Override
    public Response toResponse( Exception ex )
    {
        String method = request.getMethod();
        String pathInfo = request.getPathInfo();

        Class<?> resourceClass = resourceInfo.getResourceClass();
        Method resourceMethod = resourceInfo.getResourceMethod();
        URI resourcePath = getResourcePath( resourceClass, resourceMethod );

        URI requestUri = uriInfo.getRequestUri();
        MultivaluedMap<String, String> pathParams = uriInfo.getPathParameters();
        MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();

        // define your object to provide data through response
        Object responseEntity = ex.getMessage(); 

        // do your stuff

        return Response.status( Response.Status.INTERNAL_SERVER_ERROR )
                       .entity( responseEntity )
                       .type( MediaType.APPLICATION_JSON )
                       .build();
    }

    private static URI getResourcePath( Class<?> clazz, Method method )
    {
        if ( clazz == null || !clazz.isAnnotationPresent( Path.class ) )
        {
            return null;
        }

        UriBuilder builder = UriBuilder.fromResource( clazz );
        if ( method != null && method.isAnnotationPresent( Path.class ) )
        {
            builder.path( method );
        }

        return builder.build();
    }
}

See

Instead of Excpetion you can also map Throwable .

To pass through WebApplicationExcpetion s just add following if clause at the beginnig of toResponse() body:

if (ex instanceof WebApplicationException)
{
    return (( (WebApplicationException) ex ).getResponse());
}

You can also use all of the @Context fields in your resource class Book .

You can use the below code to log the exception from where it was thrown

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class RuntimeExceptionMapper implements ExceptionMapper<RuntimeException> {
private static final Logger logger = Logger.getLogger(yourmodule);
    @Override
    public Response toResponse(RuntimeException ex) {
        // TODO Auto-generated method stub
   logger.log(ex);
        return Response.status(Status.BAD_REQUEST).entity(ex.getMessage()).build();
    }

}

Inject in to your ExceptionMapper mapper:

@Context private ResourceInfo resourceInfo;

as it was suggested and do the following to get a method name:

resourceInfo.getResourceMethod()

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