简体   繁体   中英

Spring Boot Rest Controller endpoint exception: HttpMediaTypeNotAcceptableException

I am experiencing an issue while a mandatory field is not filled, the following exception is displayed in the logs:

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

Lets say I have an object CodeRequest that contains an attribute as follows:

@NotBlank(message = "payloadFormatIndicator.required")
@Size(max = 2, message = "payloadFormatIndicator.size")
private String payloadFormatIndicator;

My controller have the object CodeRequest as parameter as shown below:

@PostMapping(value = "/dummy", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<BufferedImage> generateQRCode(@Valid @RequestBody CodeRequest paymentRequest) throws Exception {

    log.debug("generateQRCode with the following request {}", paymentRequest);

    return ResponseEntity.status(HttpStatus.OK).body(ipsPaymentService.generateQRCode(paymentRequest));
}

When I leave the mandatory field payloadFormatIndicator empty I expect to get an error message that payloadFormatIndicator.required is required in my response.

However, I get the following error message in the log:

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

My exception handler is shown below:

@Slf4j
@ControllerAdvice

public class RestControllerExceptionHandler extends ResponseEntityExceptionHandler {
    
    @Override
    public ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException exception, HttpHeaders headers,
                                                               HttpStatus status, WebRequest request) {
        log.error(exception.getMessage(), exception);
        ExceptionResponse exceptionResponse = new ExceptionResponse(HttpStatus.BAD_REQUEST,
            exception.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    
        return new ResponseEntity<>(exceptionResponse, new HttpHeaders(), exceptionResponse.getHttpStatus());
    }

It looks like because the method generateQRCode is returning ResponseEntity<BufferedImage> it is causing this issue because for the other methods on my controller, the exception handling is working fine.

I am using swagger to test the rest API and the content type is shown below: 在此处输入图像描述

Any idea how I can fix it pls?

The issue is because of producer media-type. The response only accept image/png , yet when there is an error media-type is application/json .

change your code like this,

@PostMapping(value = "/dummy", produces = "application/json, image/png")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM