简体   繁体   English

未使用 Spring Boot 2.3 调用 RestControllerAdvice

[英]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.我想将我的应用程序从 Spring Boot 2.2.8 更新到 2.3.1 当我在更新后运行应用程序时,我的 globalExceptionHandler 将无法正常工作。 My case was to handle the error, when a invalid JSON-Body is in the request.我的情况是在请求中包含无效的 JSON-Body 时处理错误。

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 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.响应代码与之前的 400 Bad Request 一样,但响应正文为空,并且未调用我的处理程序。

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 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; Dto):JSON 解析错误:意外字符(''(代码 92)):期望双引号开始字段名称; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('' (code 92)): was expecting double-quote to start field name at [Source: (PushbackInputStream);嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('' (code 92)): was expected 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;行:8,列:54](通过参考链: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)) : 期待双引号开始字段名称; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('' (code 92)): was expecting double-quote to start field name at [Source: (PushbackInputStream);嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('' (code 92)): was expected 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; line: 8, column: 54] (通过引用链: 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] 调试 oswsmmaHttpEntityMethodProcessor - [ / ] 不匹配,支持:[] 13:13:54.016 [http -nio-8080-exec-3] 调试 oswsmmaExceptionHandlerExceptionResolver - 已解决 [org.springframework.http.converter.HttpMessageNotReadableException: JSON 解析错误:意外字符 (''-quotecode to start2): nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('' (code 92)): was expecting double-quote to start field name at [Source: (PushbackInputStream);嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('' (code 92)): was expected 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.行:8,列:54](通过参考链:com.schaerer.coffeelink.remote.boundary.v1.dto.BidiCommandDto["parameters"])] 13:13:54.016 [http-nio-8080-exec-3 ] TRACE osweb.servlet.DispatcherServlet - 没有视图渲染,null ModelAndView 返回。

Any ideas?有任何想法吗?

I've found a solution when I remove the ResponseEntityExceptionHandler extension.当我删除 ResponseEntityExceptionHandler 扩展时,我找到了一个解决方案。 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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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