简体   繁体   中英

RestControllerAdvice not called with Spring Boot 2.3

I want to update my application from Spring Boot 2.2.8 to 2.3.1 When I run the application after the update, my globalExceptionHandler won't work anymore correctly. My case was to handle the error, when a invalid JSON-Body is in the request.

Application

package com.schaerer.coffeelink.remote;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.EnableKafka;

@Slf4j
@SpringBootApplication
@EnableKafka
public class Application {

  public static void main(final String[] args) { //NOSONAR
    SpringApplication.run(Application.class, args);
    log.info("Started application. Swagger available at http://localhost:8080/swagger-ui.html");
  }
}

Controller

package com.schaerer.coffeelink.remote.boundary.v1;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.schaerer.coffeelink.remote.boundary.v1.dto.*;
import com.schaerer.coffeelink.remote.controller.v1.ActionController;
import com.schaerer.coffeelink.remote.controller.v1.BidiCommandController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@Validated
@RequestMapping(value = "v1/remote", produces = MediaType.APPLICATION_JSON_VALUE)
@Tag(name = "remote-bidi-command")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class BidiCommandResource {

  private final BidiCommandController bidiCommandController;
  private final ActionController actionController;
  private final ObjectMapper mapper;

  @ExceptionHandler({IllegalArgumentException.class})
  public ResponseEntity<Object> handleException(final IllegalArgumentException illegalArgumentException) {
    return new ResponseEntity<>(illegalArgumentException.getMessage(), HttpStatus.BAD_REQUEST);
  }

  @PostMapping
  @Operation(summary = "apply bidi command 2.0")
  public BidiCommandReturnDto applyBidiCommand(@Parameter(name = "applyBidiCommand")
                                                         @Validated({ActionDto.CreateValidation.class, BidiCommandDto.CreateValidation.class})
                                           @RequestBody final BidiCommandDto bidiCommandDto) {
        return bidiCommandController.applyBidiCommand(bidiCommandDto);
  }
}

ExceptionHandler

package com.schaerer.coffeelink.remote.boundary.v1;

import com.fasterxml.jackson.databind.JsonMappingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(value = {JsonMappingException.class})
  public ResponseEntity<Object> handleJacksonError(final JsonMappingException ex, final WebRequest request) {
    log.error("Cannot parse request. {}", request.getDescription(true), ex);
    return handleExceptionInternal(ex, ex.getMessage(), new HttpHeaders(), HttpStatus.BAD_REQUEST, null);
  }
}

I haven't change any code since the update. The response code is as before 400 Bad Request but the response body is empty and my handler isn't called.

Logs:

13:13:53.987 [http-nio-8080-exec-3] TRACE org.hibernate.internal.SessionImpl - Opened Session [6570b352-8067-49d2-bc46-c503917f4c8d] at timestamp: 1595502833972 13:13:53.991 [http-nio-8080-exec-3] TRACE ostsTransactionSynchronizationManager - Bound value [org.springframework.orm.jpa.EntityManagerHolder@72dd1712] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@38c55a8a] to thread [http-nio-8080-exec-3] 13:13:54.011 [http-nio-8080-exec-3] DEBUG oswsmmaServletInvocableHandlerMethod - Could not resolve parameter [0] in public com.schaerer.coffeelink.remote.boundary.v1.dto.BidiCommandReturnDto com.schaerer.coffeelink.remote.boundary.v1.BidiCommandResource.applyBidiCommand(com.schaerer.coffeelink.remote.boundary.v1.dto.BidiCommand Dto): JSON parse error: Unexpected character ('' (code 92)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('' (code 92)): was expecting double-quote to start field name at [Source: (PushbackInputStream); line: 8, column: 54] (through reference chain: com.schaerer.coffeelink.remote.boundary.v1.dto.BidiCommandDto["parameters"]) 13:13:54.012 [http-nio-8080-exec-3] TRACE osbfsDefaultListableBeanFactory - Returning cached instance of singleton bean 'globalExceptionHandler' 13:13:54.012 [http-nio-8080-exec-3] DEBUG oswsmmaExceptionHandlerExceptionResolver - Using @ExceptionHandler com.schaerer.coffeelink.remote.boundary.v1.GlobalExceptionHandler#handleException(Exception, WebRequest) 13:13:54.013 [http-nio-8080-exec-3] TRACE oswsmmaServletInvocableHandlerMethod - Arguments: [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('' (code 92)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('' (code 92)): was expecting double-quote to start field name at [Source: (PushbackInputStream); line: 8, column: 54] (through reference chain: com.schaerer.coffeelink.remote.boundary.v1.dto.BidiCommandDto["parameters"]), ServletWebRequest: uri=/v1/remote/;client=0:0:0:0:0:0:0:1] 13:13:54.015 [http-nio-8080-exec-3] DEBUG oswsmmaHttpEntityMethodProcessor - No match for [ / ], supported: [] 13:13:54.016 [http-nio-8080-exec-3] DEBUG oswsmmaExceptionHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('' (code 92)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('' (code 92)): was expecting double-quote to start field name at [Source: (PushbackInputStream); line: 8, column: 54] (through reference chain: com.schaerer.coffeelink.remote.boundary.v1.dto.BidiCommandDto["parameters"])] 13:13:54.016 [http-nio-8080-exec-3] TRACE osweb.servlet.DispatcherServlet - No view rendering, null ModelAndView returned.

Any ideas?

I've found a solution when I remove the ResponseEntityExceptionHandler extension. Here my solution:

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

  @ExceptionHandler(value = {HttpMessageNotReadableException.class})
  public ResponseEntity<Object> handleJacksonError(final JsonMappingException ex, final WebRequest request) {
    log.error("Cannot parse request. {}", request.getDescription(true), ex);
    return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
  }
}

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