如何在异常处理程序中更改内容类型 [英] How to change the content type in exception handler

查看:88
本文介绍了如何在异常处理程序中更改内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个控制器,该控制器为GET请求提供服务并返回要序列化为JSON的bean,并且还为IllegalArgumentException提供了可以在服务中引发的异常处理程序:

Suppose I have a controller that serves GET request and returns bean to be serialized to JSON and also provides an exception handler for IllegalArgumentException that can be raised in service:

@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);
}

消息转换器是:

<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>

现在,当我在浏览器中请求给定URL时,我会看到正确的JSON答复.但是,如果引发了异常,则将字符串化的异常也转换为JSON,但我希望它可以由StringHttpMessageConverter(导致text/plain mime类型)进行处理.我该怎么办?

Now when I request the given URL in browser I see the correct JSON reply. However if exception is raised, the stringified exception is converted into JSON as well, but I would love it to be processed by StringHttpMessageConverter (resulting text/plain mime type). How can I go it?

为使图片更完整(更复杂),假设我还具有以下处理程序:

To make the picture more complete (and complicated), suppose I also have the following handler:

@RequestMapping(value = "/version", method = RequestMethod.GET)
@ResponseBody
public String getApplicationVersion() {
    return "1.0.12";
}

此处理程序允许返回字符串由MappingJackson2HttpMessageConverterStringHttpMessageConverter进行序列化,具体取决于客户端传递的Accept-type.返回类型和值应如下:

This handler allows the return string to be serialized by both MappingJackson2HttpMessageConverter and StringHttpMessageConverter depending in passed Accept-type by the client. The return types and values should be as following:


+----+---------------------+-----------------------+------------------+-------------------------------------+
| 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          |
+----+---------------------+-----------------------+------------------+-------------------------------------+

推荐答案

我认为从getMetaInformation@RequestMapping中删除produces = MediaType.APPLICATION_JSON_VALUE会给您所需的结果.

I think removing the produces = MediaType.APPLICATION_JSON_VALUE from @RequestMapping of the getMetaInformation will give you the desired result.

响应类型将根据Accept标头中的内容类型值进行协商.

The response-type will be negotiated according to the content-type value in the Accept header.

编辑

由于这不涉及场景3,4,因此以下是直接与ResponseEntity.class一起使用的解决方案:

As this does not cover scenario 3,4 here is a solution working with ResponseEntity.class directly:

@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleIllegalArgumentException(Exception ex) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.TEXT_PLAIN);
    return new ResponseEntity<String>(ex.getMessage(), headers, HttpStatus.BAD_REQUEST);
}

这篇关于如何在异常处理程序中更改内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆