停止GlassFish包裹Jersey例外

时间:2014-03-18 15:25:01

标签: java jersey jax-rs glassfish-4

这是一个JAX-RS终点:

@Path("logout")
@POST
public void logout(@HeaderParam("X-AuthToken") String apiToken) {
    try {
        authenticationService.logout(apiToken);
    } catch (ExpiredApiTokenException exc) {
        throw new BadRequestException("API token has expired");
    } catch (InvalidApiTokenException exc) {
        throw new BadRequestException("API token is not valid");
    } catch (ApplicationException exc) {
        throw new InternalServerErrorException();
    }
}

当抛出其中一个BadRequestException(HTTP 400)时,GlassFish会在响应正文中返回自己的错误页面,而不是我的代码中的错误消息。响应包含正确的HTTP代码。只是身体被替换。

我尝试过制作ExceptionMapper

@Provider
public class ExceptionMapperImpl implements ExceptionMapper<Throwable> {

    @Override
    public Response toResponse(Throwable exception) {
        if (exception instanceof WebApplicationException) {
            return ((WebApplicationException) exception).getResponse();
        } else {
            logger.log(Level.SEVERE, "Uncaught exception thrown by REST service", exception);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    private static final Logger logger = Logger.getLogger(ExceptionMapperImpl.class.getName());
}

我尝试添加以下ejb-jar.xml:

<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         version="3.2"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd">
    <assembly-descriptor>
        <application-exception>
            <exception-class>javax.ws.rs.WebApplicationException</exception-class>
            <rollback>true</rollback>
        </application-exception>
    </assembly-descriptor>
</ejb-jar>

一切都无济于事。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

toResponse方法中,我更改了此

return exception.getResponse();

到这个

return Response.status(exception.getResponse().getStatus())
               .entity(exception.getMessage())
               .build();

问题在于我何时这样做:

throw new BadRequestException("Something is wrong!");

它不会使用Response填充异常"Something is wrong!"的正文。 GlassFish发现响应主体是空的,其状态代码是错误代码,因此它会插入自己的响应主体。通过在提供者中填充响应主体(a.k.a. entity),这个问题就消失了。