rest - 带有错误的不同内容类型编码的Spring Boot(MVC)响应

标签 rest spring-mvc error-handling spring-boot

我需要 Spring 处理错误的帮助。

客户端服务正在发送接受两种不同内容类型的请求-二进制和json。当一切正常时,我更喜欢使用二进制编码与服务器通信以节省带宽。但是在错误时,我想将ResponseEntity序列化为json,因为我的二进制序列化程序不知道如何将其序列化为二进制格式,而且它更适合日志记录等。

我配置了ResponseEntityExceptionHandler实例,并且正在处理该实现中的不同异常。但是spring总是选择二进制格式,因为它首先出现在接受(或产生)列表上。

我得到的只是(因为 Spring 不知道如何将ResponseEntity序列化为我的自定义二进制格式。请参见AbstractMessageConverterMethodProcessor#writeWithMessageConverters)

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

客户发送
headers {Accept: [application/custom-binary, application/json]

服务器的 Controller 配置为
// pseudo code
@RequestMapping(method = GET, produces = {"application/custom-binary", APPLICATION_JSON_VALUE})
public BannerMetaCollection get(@RequestParam(value = "q") UUID[] q) {
    if (q != null) {
        return service.getAllDataWith(q);
    } else {
        throw new IllegalArgumentException("invalid data");
    }
}

// pseudo code
public class RestExceptionResolverSupport extends ResponseEntityExceptionHandler {
    @ExceptionHandler
    public ResponseEntity<Object> illegalArgumentException(IllegalArgumentException ex, WebRequest request {
        Object body = errorResponse()
                    .withCode(BAD_REQUEST)
                    .withDescription("Request sent is invalid")
                    .withMessage(ex.getMessage())
                    .build());
        return new ResponseEntity<Object>(body, new HttpHeaders(), HttpStatus.BAD_REQUEST);
    }
}

有什么提示吗?

最佳答案

我要做的是让我的终结点方法返回ResponseEntity,而我不声明@RequestMapping批注中产生了什么内容。然后我在返回响应之前自行设置Content-type header ,例如

// pseudo code
@RequestMapping(method = GET)
public ResponseEntity<BannerMetaCollection> get(@RequestParam(value = "q") UUID[] q) {
    if (q != null) {
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "application/custom-binary");
        return new ResponseEntity<>(service.getAllDataWith(q),
                headers,
                HttpStatus.OK);
    } else {
        throw new IllegalArgumentException("invalid data");
    }
}

关于rest - 带有错误的不同内容类型编码的Spring Boot(MVC)响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30573324/

相关文章:

java - 从void返回字符串

java - Spring Data Rest - Bean 验证未应用于 PUT 方法?

api - 是否应在API中对分页进行零索引?

url - 让 Spring 告诉 FreeMarker 要使用的 URL 编码

spring - 如何从 Controller 向 "j_spring_security_check"发送请求

c - 为什么警告 : assignment from incompatible pointer type?

rest - 如何在 Node.js 中进行远程 REST 调用?任何 curl ?

java - 在 Android Studio 中使用 Google 翻译 API

java - 如何使用 java 配置运行 Spring http 调用程序

java - 在 Spring Boot 中,如何在显示 error.html 之前捕获错误并对其进行处理?