API Different Content
Since some weeks I'm working on an rest api using spring-mvc. The REST-API is working properly and I`m almost done until one last problem when it comes to error handling with specific error-objects.
The REST-API is using JSON as format to serialize Java-Objects. When an error occurs during service-execution an specific error-object gets created and sent back to the client.
Everything is working fine when my rest-services are marked as "produces=application/json". But there are also some services which only need to return simple text using "produces=text/plain". When an error occurs in one of these services Spring-MVC will throw an HttpMediaTypeNotAcceptableException. Seems to be correct cause client asks for content-type "text/plain" but server response with "application/json".
Can you tell me what's the correct solution for this problem?
Only using JSON as response content-type and wrapping simple text always in an special class object. => Seems to me not really REST like, cause REST should support multiple content-types.
Every service serving "text" will be marked as "produces=application/json;text/plain" and Client also need to send both in "accept-header". => When doing it this way the API seems to support two content-types for same resource. But that`s not right. Only in case of an error the API will return JSON, otherwise it will be always "text".
Sounds for me like a really special REST question and couldn`t find related questions on this topic.
User should always specify what content it's expecting with Accept
header. It's you job to return the error that was thrown/caught on the server side in the format that was specified in Accept
header. In spring as far as I know it could be achieved with a special mapper. Below you can find such mapper written in groovy to handle 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
}
}
And ExceptionResponse
class:
class ExceptionResponse {
String error
String exception
String message
String path
Integer status
Long timestamp
}
链接地址: http://www.djcxy.com/p/48186.html
上一篇: 如何通过spring RestTemplate在获取请求中更改响应http头?
下一篇: API不同的内容