Como alterar o tipo de conteúdo no manipulador de exceções
Suponha que eu tenha um controlador que serveGET
solicita e retorna o bean a ser serializado para JSON e também fornece um manipulador de exceção paraIllegalArgumentException
que pode ser levantado em serviço:
@RequestMapping(value = "/meta/{itemId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public MetaInformation getMetaInformation(@PathVariable int itemId) {
return myService.getMetaInformation(itemId);
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public String handleIllegalArgumentException(IllegalArgumentException ex) {
return ExceptionUtils.getStackTrace(ex);
}
Conversores de mensagens são:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven>
Agora, quando eu solicito o URL fornecido no navegador, vejo a resposta JSON correta. No entanto, se a exceção for levantada, a exceção esticada será convertida em JSON também, mas eu adoraria que ela fosse processada porStringHttpMessageConverter
(resultandotext/plain
tipo mime). Como eu posso ir?
Para tornar a imagem mais completa (e complicada), suponha que eu também tenha o seguinte manipulador:
@RequestMapping(value = "/version", method = RequestMethod.GET)
@ResponseBody
public String getApplicationVersion() {
return "1.0.12";
}
Este manipulador permite que a string de retorno seja serializada por ambosMappingJackson2HttpMessageConverter
eStringHttpMessageConverter
dependendo do passadoAccept-type
pelo cliente. Os tipos e valores de retorno devem ser os seguintes:
+----+---------------------+-----------------------+------------------+-------------------------------------+ | NN | URL | Accept-type | Content-type | Message converter | | | | request header | response header | | +----+---------------------+-----------------------+------------------+-------------------------------------+ | 1. | /version | text/html; */* | text/plain | StringHttpMessageConverter | | 2. | /version | application/json; */* | application/json | MappingJackson2HttpMessageConverter | | 3. | /meta/1 | text/html; */* | application/json | MappingJackson2HttpMessageConverter | | 4. | /meta/1 | application/json; */* | application/json | MappingJackson2HttpMessageConverter | | 5. | /meta/0 (exception) | text/html; */* | text/plain | StringHttpMessageConverter | | 6. | /meta/0 (exception) | application/json; */* | text/plain | StringHttpMessageConverter | +----+---------------------+-----------------------+------------------+-------------------------------------+