spring-projects / spring-framework

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

Support "application/problem+json" as the response Content-Type #28189

Closed rstoyanchev closed 2 years ago

rstoyanchev commented 2 years ago

Once #28187 provides ProblemDetail along with the ErrorResponse hierarchy of exceptions that encapsulate HTTP status, headers, and body, to support RFC 7807, it is also necessary to improve content negotiation and formatting specifically for error responses.

In Spring MVC it is possible to configure content type resolution and message conversion and likewise in WebFlux to configure content type resolution and message codecs, but those apply to both @RequestMapping and @ExceptionHandler methods.

Error handling however has a different perspective. The range of supported media types might be more limited and different, e.g. only application/problem+json. The resolution of the request content type might also be done differently, .e.g. defaulting to application/problem+json if not explicitly requested, or perhaps even enforcing it.

Such a mechanism is also a convenient place for other configuration related to how ProblemDetail should be rendered..

rstoyanchev commented 2 years ago

On closer investigation, this can be handled transparently as follows.

Message converters and encoders indicate a preference for application/problem+json when ProblemType is serialized. This ensures application/problem+json is preferred when the client is flexible or has no preference.

If content negotiation fails to find an acceptable media type for serializing ProblemDetail, we try again with application/problem+json and application/problem+xml as the acceptable media types, in effect enforcing a fallback for ProblemDetail.