【问题标题】:spring boot (mvc) response with different content type encoding on error错误时具有不同内容类型编码的spring boot(mvc)响应
【发布时间】:2015-06-01 12:18:03
【问题描述】:

我需要有关 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]

服务器的控制器配置为

// 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);
    }
}

有什么提示吗?

【问题讨论】:

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


    【解决方案1】:

    我要做的就是让我的端点方法返回一个ResponseEntity,并且我没有声明在@RequestMapping 注释中产生了什么内容。然后我在返回响应之前自己设置 Content-type 标头,例如

    // 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");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 2017-05-02
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 2021-10-08
      • 2011-04-06
      • 1970-01-01
      • 2017-11-28
      相关资源
      最近更新 更多