我正在JAX-RS上的Web服务工作.现在我正在寻找一种方法来捕获一些异常,以便向用户发送一条40X错误的自定义消息.
我有一个Web服务和一个ExceptionMapper.
这是我的网络服务:
@Path( value = "/test/")
public interface ServiceTest {
@Path(value = "{rrf}")
@GET
@Produces(MediaType.TEXT_XML)
public ObjectDTO getDealer(@PathParam("rrf") String rrf){
ObjectDTO objectDTO = new ObjectDTO();
if( verifyRRFSintax(rrf) ) {
//Get the objet,this part works fine
} else {
throw new IllegalArgumentException("Custom message");
}
return dwsDTO;
}
private boolean verifyRRFSintax(String rrf) {
return rrf.matches("[0-9]{8}");
}
}
这是我的ExceptionMapper
@Provider
@Produces(MediaType.TEXT_XML)
public class IllegalArgumentExceptionMapper
implements ExceptionMapper<IllegalArgumentException> {
@Override
public Response toResponse(IllegalArgumentException e) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
这就是它在application-context.xml文件中的注册方式
<bean id="serviceTest" class="ServiceTest"/>
<jaxrs:server id="Server" address="/ws">
<jaxrs:serviceBeans>
<ref bean="serviceTest"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean id="rffErrorException" class="IllegalArgumentExceptionMapper"/>
</jaxrs:providers>
</jaxrs:server>
当我调试时,IllegalArgumentExceptionMapper捕获异常我抛出,但我看不到在浏览器上显示的黄色网页上的消息.我总是有一个
Erreur d’analyse XML : aucun élément trouvé / XML Parsing Error: no
element found (in english)
我怎样才能在浏览器上显示这个自定义消息?
为什么,即使我改变了响应状态(NOT_FOUND,BAD_REQUEST,FORBIDDEN)的类型,这个黄页总是一样的?
PD:在控制台上,我有一个消息“out.handlemessage”,当Mapper捕获异常时打印.
谢谢.
解决方法
throw new WebApplicationException(Response.status(Status.NOT_FOUND)// Or another Status
.entity("Error Message").build());