springdoc-openapi icon indicating copy to clipboard operation
springdoc-openapi copied to clipboard

Controller advice documents ApiResponse on every operation, even if the operation does not annotate the exception to be thrown

Open jamesbradlee opened this issue 1 year ago • 1 comments

Describe the bug

Exception handlers annotated with @ApiResponse and @ResponseStatus seem to be applied to all operations, even if the implementing operation method handler does not throw the exception handled by the exception handler.

To Reproduce Steps to reproduce the behavior:

  • spring-boot: 3.2.1
  • org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0
  • What is the actual and the expected result using OpenAPI Description (yml or json)?
  • Provide with a sample code (HelloController) or Test that reproduces the problem
data class HelloResponse(val value: String)

@RestController
class HelloController {
  @GetMapping("/hello")
  @Operation(operationId = "hello", summary = "Hello, World!")
  fun hello() = HelloResponse("World")

  @GetMapping("/greet/{name}")
  @Operation(operation = "greet", summary = "Hello someone!")
  @Throws(InvalidNameException::class)
  fun greet(@PathVariable name: String) = throw InvalidNameException("Name '$name' is invalid!")
}

@ControllerAdvice
class HelloAdvisor {
  @ExceptionHandler(InvalidNameException::class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ApiResponse(description = "The provided name is invalid", useReturnScheme = true)
  fun handleNameException(e: InvalidNameException): MyErrorResponse {
    TODO()
  }
}

Expected behavior

I would expect only the greeting operation to be documented with the invalid name exception, but the hello exception is also documented with it.

jamesbradlee avatar Jan 14 '24 17:01 jamesbradlee

I have the same problem

iosonopersia avatar Feb 02 '24 16:02 iosonopersia

@iosonopersia and @testersen,

I have added a fix for this request. You can validate it already based on the Latest SNAPSHOT

bnasslahsen avatar Mar 11 '24 16:03 bnasslahsen

@bnasslahsen I can confirm you that, by using version 2.3.1-SNAPSHOT, the problem is completely gone and everything seems to work as expected. Thank you for the effort, looking forward to the release of version 2.3.1!

iosonopersia avatar Mar 12 '24 10:03 iosonopersia

Good work @bnasslahsen, look forward to see it hit 2.3.1! :)

jamesbradlee avatar Mar 12 '24 12:03 jamesbradlee