JAX-RS jersey ExceptionMapper:如何知道抛出异常的方法

时间:2016-12-23 12:16:46

标签: java rest jersey jax-rs

我正在使用JAX-RS jersey ExceptionMapper,我想知道是否有办法知道方法toResponse(),哪个方法(来自API)抛出异常。

示例(虚拟代码)

@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();
    }
}

3 个答案:

答案 0 :(得分:3)

您可以从上下文向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();
    }
}

您可以映射Excpetion

而不是Throwable

要通过WebApplicationExcpetion,只需在toResponse()正文的开头添加以下if子句:

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

您还可以使用资源类@Context中的所有Book字段。

答案 1 :(得分:0)

您可以使用以下代码记录引发异常的异常

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();
    }

}

答案 2 :(得分:0)

注入ExceptionMapper映射器:

@Context private ResourceInfo resourceInfo;

建议并执行以下操作以获取方法名称:

resourceInfo.getResourceMethod()