我需要 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/