spring-projects / spring-framework

Spring Framework
https://spring.io/projects/spring-framework
Apache License 2.0
56.27k stars 37.98k forks source link

Add types to represent RFC 7807 problem details and exceptions #28187

Closed rstoyanchev closed 2 years ago

rstoyanchev commented 2 years ago

The goal for this issue is to add a representation for an RFC 7807 problem detail, and integrate it into Spring MVC and Spring WebFlux error response handling.

On the WebFlux side we have the ResponseStatusException hierarchy which contains HTTP status, a reason, and headers. We can now add a ProblemDetail as the body. This provides full encapsulation of all error response details within the exception.

On the Spring MVC side, we have the DefaultHandlerExceptionResolver which maps exceptions to HTTP status and headers, so exceptions do not themselves contain that information. Furthermore the exception hierarchy does not have a single base class where this can be added. We can add an interface to represent an error response, e.g. ErrorResponse, similar to the information exposed from ResponseStatusException on the WebFlux side, and then have all Spring MVC exceptions implement it in order to expose it in which case DefaultHandlerExceptionResolver no longer needs mapping logic.

ResponseEntityExceptionHandler is a base class for a controller advice that uses an @ExceptionHandler method to render error details. It has been around for some time, but so far application have had to extend it to decide on the error body format. We can now fill in the blank and use ProblemDetail for ResponseError exceptions that expose such information. A similar class does not exist for WebFlux but can be added.

ResponseEntity handling for both Spring MVC and WebFlux should support ProblemDetail and ErrorResponse as return types, automatically setting the response status, headers, and body accordingly. This is also an opportunity to set the instance field of ProblemDetail to the request path as a fallback if instance hasn't been set.

rstoyanchev commented 2 years ago

See commits linked the umbrella issue #27052.