Java SpringBoot和ProtoBuf:如何通过在响应体中添加错误来使HTTP 400s更有用?

Java SpringBoot和ProtoBuf:如何通过在响应体中添加错误来使HTTP 400s更有用?,java,spring,spring-boot,protocol-buffers,protobuf-java,Java,Spring,Spring Boot,Protocol Buffers,Protobuf Java,我们正在使用ProtobufJsonFormatHttpMessageConverter将JSON请求主体解析为REST端点中的protos: @Bean ProtobufHttpMessageConverter protobufHttpMessageConverter() { return new ProtobufJsonFormatHttpMessageConverter( JsonFormat.parser(), JsonFormat.printer().i

我们正在使用
ProtobufJsonFormatHttpMessageConverter
将JSON请求主体解析为REST端点中的protos:

  @Bean
  ProtobufHttpMessageConverter protobufHttpMessageConverter() {
    return new ProtobufJsonFormatHttpMessageConverter(
        JsonFormat.parser(), JsonFormat.printer().includingDefaultValueFields());
  }
在请求中,假设有一个枚举,如果值中有输入错误,例如

{
     "type": "ELEPHAANT"
}
我返回了一个带有空正文的
HTTP 400
响应,控制台有:

DEBUG o.s.w.s.DispatcherServlet - POST "/foo-search", parameters={}
DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped to com.foobar.MasterController#sample(SampleRequest)
DEBUG o.s.w.s.m.m.a.ServletInvocableHandlerMethod - Could not resolve parameter [0] in public com.foobar.models.ResponseOuterClass$SampleResponse com.foobar.MasterController.Sample(com.foobar.models.SampleRequestOuterClass$SampleRequest): I/O error while reading input message; nested exception is com.google.protobuf.InvalidProtocolBufferException: Invalid enum value: ELEPHAANT for enum type: SampleRequest.Filter.Type
DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Using @ExceptionHandler com.foobar.advice.ExceptionHandlerAdvice#handleException(Exception, WebRequest)
DEBUG o.s.w.s.m.m.a.HttpEntityMethodProcessor - No match for [*/*], supported: []
DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is com.google.protobuf.InvalidProtocolBufferException: Invalid enum value: ELEPHAANT for enum type: ObtSampleRequest.Filter.Type]
DEBUG o.s.w.s.DispatcherServlet - Completed 400 BAD_REQUEST
控制台日志中清楚地显示了该问题:

Invalid enum value: ELEPHAANT for enum type: ObtSampleRequest.Filter.Type

我是否可以通过包含上述信息使响应正文更有用?

您可以提出@RestControllerAdvice

@RestControllerAdvice
public class MyAdvice {

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handle(HttpMessageNotReadableException e) {
       return e.getMessage(); // or return a nice error object with the nested exception's msg
  }

}