gpt4 book ai didi

java - HttpMediaTypeNotAcceptableException 对于文本/纯消息响应的错误?

转载 作者:IT老高 更新时间:2023-10-28 13:44:31 25 4
gpt4 key购买 nike

我有一个简单的 web 服务,它以 jsonplain text 形式返回内容(取决于客户端的 accept http header )。

问题:如果在 text/plain 请求期间发生错误,Spring 会以某种方式返回 406 Not Acceptable。这是错误的,因为 spring 也可以将错误写为纯错误文本,而且应该绝对保留 400 错误状态:

@RestController
public class TestServlet {
@PostMapping(value = "/test", produces = {APPLICATION_JSON_VALUE, TEXT_PLAIN_VALUE, "text/csv"})
public Object post() {
throw new BadRequestException("bad req");
}
}

@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String msg) {
super(msg);
}
}

带有 accept=application/json 的 POST 请求:

{
"timestamp": "2018-07-30T14:26:02",
"status": 400,
"error": "Bad Request",
"message": "bad req",
"path": "/test"
}

但带有 accept=text/csv(或 text/plain)的结果显示空响应,状态为 406 Not Acceptable

我还注意到 DispatcherServlet.processDispatchResult() 被调用了两次:第一次是我的 BadRequest 异常,第二次是 HttpMediaTypeNotAcceptableException。很明显,我的自定义异常的呈现失败了,但是为什么?

最佳答案

问题是限制性的 Accept header 只允许一种内容类型作为响应。如果发生错误,Spring MVC 需要处理 BadRequestException 并使用已注册的 HttpMessageConverter 生成所需的内容类型。

默认情况下,Spring Boot 没有直接从任何对象生成 text/plain 的消息转换器。您可以注册一个 ObjectToStringHttpMessageConverter (因为 bean 应该适用于 Spring Boot)以允许这样做,您将获得 BadRequestException.toString() 的结果作为响应正文。

我假设 text/csv 存在类似问题,但我不确定您的 CSV 消息转换设置是什么样的。

关于java - HttpMediaTypeNotAcceptableException 对于文本/纯消息响应的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51594072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com