代码之家  ›  专栏  ›  技术社区  ›  Shane Rowatt

spring rest控制器不支持的媒体类型或没有处理程序

  •  0
  • Shane Rowatt  · 技术社区  · 5 年前

    如果我有这样的弹簧休息控制器

    @PostMapping( 
        value = "/configurations",
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseStatus(HttpStatus.CREATED)
    public CreateConfigurationResponse createConfiguration(
        @RequestBody @Valid @NotNull final CreateConfigurationRequest request) {
        // do stuff
    }
    

    客户端使用 Accept 头球,然后弹簧抛出 HttpMediaTypeNotAcceptableException . 然后我们的异常处理程序捕获它并构造 Problem (RFC-7807)错误响应

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ControllerAdvice
    public class HttpMediaTypeExceptionHandler extends BaseExceptionHandler {
    
        @ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
        public ResponseEntity<Problem> notAcceptableMediaTypeHandler(final HttpMediaTypeNotAcceptableException ex,
            final HttpServletRequest request) {
    
        final Problem problem = Problem.builder()
            .withType(URI.create("...."))
            .withTitle("unsupported media type")
            .withStatus(Status.NOT_ACCEPTABLE)
            .withDetail("...error stuff..")
            .build();
    
        return new ResponseEntity<>(problem, httpStatus);
    }
    

    但是自从 问题 应使用媒体类型发送错误响应 application/problem+json 然后spring将其视为不可接受的媒体类型,并调用 HttpMediaTypeExceptionHandler 异常处理程序再次指出媒体类型不可接受。

    在spring中,是否有方法停止进入异常处理程序的第二个循环,即使accept头不包括 应用程序/问题+json 媒体类型它还是会返回那个?

    0 回复  |  直到 5 年前
        1
  •  0
  •   Shane Rowatt    5 年前

    奇怪的是,当我将return语句从这里改为:

    return new ResponseEntity<>(problem, httpStatus);
    

    对此:

    return ResponseEntity
            .status(httpStatus)
            .contentType(MediaType.APPLICATION_PROBLEM_JSON)
            .body(problem);
    

    我不知道这是怎么做到的,但它确实做到了。