REST-API of various types of content on error

For some weeks I have been working on rest api using spring -mvc. The REST-API is working correctly, and I almost do until the last problem when it comes to handling errors using specific error objects.

The REST API uses JSON as a format for serializing Java objects. If an error occurs during the execution of the service, a specific error object is created and sent back to the client.

Everything works fine when my leisure services are marked as "produces = application / json". But there are also some services that should return only plain text using "results = text / plain". If an error occurs in one of these services, spring-MVC will throw an HttpMediaTypeNotAcceptableException. It seems correct, the client is requesting a text / plain text type, but the server response is "application / json".

Can you say what is the right solution for this problem?

  • Only using JSON as the type of response content and wrapping plain text is always in a special class object. => I don't seem to like REST because REST should support several types of content.

  • Each service serving the "text" will be marked as "produces = application / json; text / plain", and the client also needs to send both to the "accept-header". => In doing so, the API API seems to support two types of content for the same resource. But this is wrong. Only in case of an error the API will return JSON, otherwise it will always be "text".

It sounds to me like a really special REST question and cannot find related questions on this topic.

+4
source share
1 answer

, Accept. , , / , Accept. spring , . , groovy, text/html.

import groovy.xml.MarkupBuilder
import org.springframework.http.HttpInputMessage
import org.springframework.http.HttpOutputMessage
import org.springframework.http.converter.AbstractHttpMessageConverter

import static org.springframework.http.MediaType.TEXT_HTML

class ExceptionResponseHTMLConverter extends AbstractHttpMessageConverter<ExceptionResponse> {
  ExceptionResponseHTMLConverter() {
    super(TEXT_HTML)
  }

  @Override
  boolean supports(Class clazz) {
    clazz.equals(ExceptionResponse)
  }

  @Override
  ExceptionResponse readInternal(Class clazz, HttpInputMessage msg) {
    throw new UnsupportedOperationException()
  }

  @Override
  void writeInternal(ExceptionResponse e, HttpOutputMessage msg) {
    def sw = new StringWriter()
    new MarkupBuilder(sw).error {
      error(e.error)
      exception(e.exception)
      message(e.message)
      path(e.path)
      status(e.status)
      timestamp(e.timestamp)
    }
    msg.body << sw.toString().bytes
  }
}

ExceptionResponse :

class ExceptionResponse {
  String error
  String exception
  String message
  String path
  Integer status
  Long timestamp
}
+2

All Articles