1

Is there a place where it is clearly documented that I cannot map UnsupportedMediaTypeException (because it's a rest easy exception and not custom application exception) using the javax.ws.rs.ext.ExceptionMapper?

I want to prove that to my client. Or another thing I would like to do is map this exception to a Response that can be fetched at the client to show the error. Right now when this exception is thrown it provides no information to the client as the application ends abruptly.

Any help would be appreciated.

Thanks

4

1 回答 1

1

您可以映射此异常。为什么不?你有错误吗?

这段代码应该可以完成这项工作

@Provider
public class EJBExceptionMapper implements ExceptionMapper<org.jboss.resteasy.spi.UnsupportedMediaTypeException>{

  Response toResponse(org.jboss.resteasy.spi.UnsupportedMediaTypeException exception) {
    return Response.status(415).build();
  }

}

不要忘记在 Spring 配置文件中声明该提供程序。

如果您想向客户端创建类提供更多信息

@XmlRootElement
public class Error{
   private String message;
   //getter and setter for message field
}

然后你可以

@Provider
public class EJBExceptionMapper implements ExceptionMapper<org.jboss.resteasy.spi.UnsupportedMediaTypeException>{

  Response toResponse(org.jboss.resteasy.spi.UnsupportedMediaTypeException exception) {
    Error error = new Error();
    error.setMessage("Whatever message you want to send to user");
    return Response.entity(error).status(415).build();
  }

}

如果您不想使用错误实体,只需传递一个字符串即可Response.entity()调用。

如果您想捕获应用程序中抛出的任何内容,请创建通用异常映射器:

@Provider
public class ThrowableMapper implements ExceptionMapper<Throwable> {

    public Response toResponse(Throwable t) {

        ErrorDTO errorDTO = new ErrorDTO(code);
        return Response.status(500).build();
    }
}
于 2012-04-26T12:12:44.373 回答