java - 在 Jersey 中显示图像 ExceptionMapper

标签 java rest jersey jax-rs

我尝试为 CompletionException 编写自定义异常映射器,并在出现此异常时显示图像。这是我的映射器:

@Provider
public class CustomCompleteExceptionManager implements ExceptionMapper<CompletionException> {

    @Override
    public Response toResponse(CompletionException e) {
        return Response
                .status(Response.Status.BAD_REQUEST)
                .entity(Paths.get("error.png").toFile())
                .type("image/img")
                .build();
    }

当我的代码抛出 CompletionException 但浏览器不显示 error.png 时,会调用 toResponse 方法。我收到错误:

This site can’t be reached

The webpage at http://localhost:8080/cf/point might be temporarily down or it may have moved permanently to a new web address.

当我只将字符串消息写入 Response 时,它工作正常:

@Provider
public class CustomCompleteExceptionManager implements ExceptionMapper<CompletionException> {

    @Override
    public Response toResponse(CompletionException e) {
        return Response
                .status(Response.Status.BAD_REQUEST)
                .entity(e.getMessage())
                .build();
    }

可能是什么问题?

最佳答案

响应中设置的媒体类型错误。
它应该是 .type("image/png") 而不是 image/img

这是我在本地测试时的代码。

return Response
            .status(Response.Status.BAD_REQUEST)
            .entity(Paths.get("/home","kishore","Pictures","Meme.png").toFile())
            .type("image/png")
            .build();

关于java - 在 Jersey 中显示图像 ExceptionMapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41779169/

相关文章:

java: 如何给 JFrame 添加透明渐变背景

linux - Curl 作为 REST 服务器

java - SSL/TLS 版本兼容性?

java类型转换困惑

java - 服务器(Python)-使用套接字的客户端(Java)通信

java - Mac OS X 上 IntelliJ IDEA 中的 JDK 文档

java - 获取 ArtifactDescriptorException : Failed to read artifact descriptor for org. glassfish.jersey.media :jersey-media-moxy:jar:2. 22.1

rest - 如何为同一个 Azure blob 生成多个临时访问 URL?

php - Laravel 5 REST 客户端增删改查

java - 另一个 Guice + Jersey 错误 NoSuchMethodError