1

My application has an REST interface and I must customize the rendering of the result body in case that a controller returns ResponseEntity<>(NOT_FOUND) as the controller with the following method it does:

@Override
public ResponseEntity<ScimCoreUser> getUserById(String userid) {
    Optional<ScimCoreUser> result = service.findUserByNumber(userid);

    return result.map(user -> new ResponseEntity<>(user, HttpStatus.OK))
                 .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}

I cannot change the signature of the method, as I must impement a generated interface. I know what I could simple throw a custom exception and handle this exception with a controller advice.

Does someone know how to take over the rendering of the result body for ResponseEntity<>(HttpStatus.NOT_FOUND)), so that I can return an error message in the following format as defined in RFC 7644: System for Cross-domain Identity Management: Protocol:

{
    "schemas": ["urn:ietf:params:scim:api:messages:2.0:Error"],
    "detail":"Resource 2819c223-7f76-453a-919d-413861904646 not found",
    "status": "404"
}
Community
  • 1
  • 1
Oliver
  • 3,815
  • 8
  • 35
  • 63

2 Answers2

1

SCIM protocol & Spring

Not experienced with SCIM but found a related question: SCIM implementation for Spring Boot SAML and OKTA

Spring response magic: extension points

For "rendering", or converting response-entities to HTTP responses Spring uses subclasses of HttpMessageConverter. This bean would be a candidate to define and inject in your web-config.

Spring allows to enrich/extend the error-attributes converted and sent as error-response: Spring Boot customize http error response?

The error-messages used for enriching a HTTP error response body like NOT_FOUND (404) are either defined by a message-bundle (properties file with I18N support) or set within the response filter-chain.

The actual rendering, if JSON, plain text, HTML, etc. is done by Spring upon content-negotiation with requesting HTTP-client. However, you could override the method in controller and specify parameters consumes, produces to @RequestMapping annotation.

hc_dev
  • 8,389
  • 1
  • 26
  • 38
  • 1
    I step through the code and Spring calls only a message converter, if the body, that is, the payload, if not null. In my case the message is null and therefore no message converter is called. – Oliver Apr 01 '21 at 21:19
  • @Oliver Sorry I didn't research further. So, could you add a body to trigger the _converter_? Otherwise some status-code serialisation is certainly performed by Spring too!? – hc_dev Apr 01 '21 at 21:23
0

You could use

return result.map(user -> new ResponseEntity<>(user, HttpStatus.OK))
                 .orElseThrow(() -> 
                      new ResponseStatusException(
                            HttpStatus.NOT_FOUND, "User not found");
Kaj Hejer
  • 955
  • 4
  • 18