【发布时间】: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