【问题标题】:MediaTypeNotAcceptable with SpringBoot RestControllerSpring Boot Rest Controller 不接受 MediaType
【发布时间】:2019-05-10 07:50:36
【问题描述】:

我有一个带有生成媒体类型“Plain_text”的 GetMapping 的休息控制器。当底层服务发生异常时,将由控制器通知处理,控制器通知返回一个将序列化为 JSON 的对象。

在服务没有抛出任何异常的快乐路径中,我得到了正确的响应。但在出现错误情况时,我会收到错误“找不到可接受的表示”的异常。如果我删除了生产标签,则控制器工作正常。

spring boot 有没有办法让 api 返回纯文本媒体类型,如果出现错误,返回 Json 响应?

这是我的代码:

@RestController
@RequestMapping("/sample")
public class SampleController() {

   @Autowired
   SampleService service;

   @GetMapping(produces = MediaType.TEXT_PLAIN)
   public String getString(){
      return service.getString();
   }

}

控制器建议:

@RestControllerAdvice
public class SampleControllerAdvice(){

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({SampleNotFoundException.class})
    public SampleErrorResponse handleException(Exception ex) {
        return new SampleErrorResponse(e.getMessage());
    }

}

【问题讨论】:

  • 首先,你能把你的方法的参数放在你的控制器中吗?第三点,你如何测试你得到休息的方法?

标签: spring-boot controller media-type


【解决方案1】:

这看起来与 SPR-16318 相关,它已在 Spring Framework 5.1 中修复 - 这是 Spring Boot 2.1 中使用的版本。

您应该升级到 Spring Boot 2.1+ 以在您的应用程序中获得该修复。

【讨论】:

    猜你喜欢
    • 2018-02-28
    • 1970-01-01
    • 2020-10-29
    • 2018-10-05
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    相关资源
    最近更新 更多