resterror-handlingcontent-typehttp-accept-header

How to handle error responses in a REST endpoint that accepts different Accept header values.


I'm trying to add a new content type to a REST endpoint. Currently it only returns json but I now need to be able to return also a CSV file.

As far as I know, the best way to do this is by using the Accept header with value text/csv and then add a converter that is able to react to this and convert the returned body to the proper CSV representation.

I've been able to do this but then I have a problem handling exceptions. Up until know, all the errors returned are in json. The frontend expects any 500 status code to contain a specific body with the error. But now, by adding the option to return either application/json or text/csv to my endpoint, in case of an error, the converter to be used to transform the body is going to be either the jackson converter or my custom one depending on the Accept header passed. Moreover, my frontend is going to need to read the content-type returned and parse the value based on the type of representation returned.

Is this the normal approach to handle this situation?

A faster workaround would be to forget about the Accept header and include a url parameter indicating the format expected. Doing it this way, I'd be able to change the content-type of the response and the parsing of the data directly in the controller as the GET request won't include any Accept header and it will be able to accept anything. There are some parts of the code already doing this where the only expected response format is CSV so I'm going to have a difficult time defending the use of the Accept header unless there is a better way of handling this.


Solution

  • my frontend is going to need to read the content-type returned and parse the value based on the type of representation returned.

    Is this the normal approach to handle this situation?

    Yes.

    For example, RFC 7807 describes a common format for describing problems. So the server would send an application/problem+json or an application/problem+xml representation of the issue in the response, along with the usual meta data in the headers.

    Consumers that understand application/problem+json can parse the data with in, and forward a useful description of the problem to the user/logs whatever. Consumers that don't understand that representation are limited to acting on the information in the headers.

    A faster workaround would be to forget about the Accept header and include a url parameter indicating the format expected.

    That's also fine -- more precisely, you can have a different resource responsible for the each of the different media-types that you support.

    It may be useful to review section 3.4 of RFC 7231, which describes the semantics of content negotiation.