使用 ExceptionMapper 映射不支持的媒体类型异常



有没有一个地方清楚地记录了我无法使用javax.ws.rs.ext.ExceptionMapper映射UnsupportedMediaTypeException(因为它是一个轻松的异常而不是自定义应用程序异常)?

我想向我的客户证明这一点。或者我想做的另一件事是将此异常映射到可以在客户端获取以显示错误的响应。现在,当引发此异常时,它不会向客户端提供任何信息,因为应用程序会突然结束。

任何帮助将不胜感激。

谢谢

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

此代码应该完成这项工作

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

最新更新