Spring rest controller @ExceptionHandler返回xml内容和json错误

时间:2017-10-18 10:31:19

标签: java spring spring-restcontroller

所以我有一个@RestController,我希望根据前端应用程序的模式返回并验证XML,以便在编辑器中显示它们。我希望错误是json格式,以便用js处理和显示它们。

$Server = Get-Content servers.txt
$OutArray = @()
$output = foreach ($Server in $Server) {
    $IP = [System.Net.Dns]::GetHostAddresses($Server)
    $OutArray += $Server + "  " + $IP.IPAddressToString
}

$OutArray | Out-File IPs.txt

ServerError我想以JSON格式返回:

@RestController
public class UserController {

    @RequestMapping(value = "/test",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_XML_VALUE)
    public ResponseEntity<String> throwException(
        @RequestParam(value = "flag", defaultValue = "false") Boolean flag
    ) throws Exception {
        if (flag) {
            throw new Exception();
        } else {
            return ResponseEntity.ok("<xml>hello</xml>");
        }
    }


    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    ServerError exceptionHandler(HttpServletRequest req, Exception ex) {
        return new ServerError(req.getRequestURL().toString(),ex);
    }

}

所以public class ServerError { public final String url; public final String error; public ServerError(String url, Exception ex) { this.url = url; this.error = ex.getMessage(); } public String getUrl() { return url; } public String getError() { return error; } } 返回就好了但是当我将标志设置为<xml>hello</xml>时我得到了

true

此外,将ERROR 2017-10-18 12:56:53,189 [http-nio-0.0.0.0-8080-exec-2] org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Failed to invoke @ExceptionHandler method: eu.openminted.registry.core.exception.ServerError eu.openminted.registry.service.UserController.malformedExeption(javax.servlet.http.HttpServletRequest,java.lang.Exception) org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation 设置为XML和JSON会产生相同的结果

produces

3 个答案:

答案 0 :(得分:3)

我设法通过从@RequestMapping(value = "/test", method = RequestMethod.GET, produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_UTF8_VALUE}) 移除produces并使用@RequestMapping指定我想要返回的类型来解决此问题

ResponseEntity

该解决方案的问题在于,所有方法的@RequestMapping(value = "/test", method = RequestMethod.GET) public ResponseEntity<String> throwException( @RequestParam(value = "flag", defaultValue = "false") Boolean flag ) throws Exception { if (flag) { throw new Exception(); } else { ResponseEntity response = ResponseEntity.ok(). contentType(MediaType.APPLICATION_XML). body("<xml>hello</xml>"); return response; } } 都具有@annotation类型,并且不会产生一致性。

答案 1 :(得分:1)

您需要在pom.xml中添加以下依赖项,它将与您的代码一起使用produce = MediaType.APPLICATION_XML_VALUE,

[
    {
        "role": "admin",
        "id": "59df4ef2d8d39",
        "email": "a@a.dk",
        "name": "A",
        "lastname": "A",
        "password": "1",
        "image": "img_webshop\/userimage-59dfb91515810.png"
    },
    {
        "role": "user",
        "id": "59df4f1b070e6",
        "phonenumber": "12345678",
        "name": "B",
        "lastname": "B",
        "password": "2",
        "image": "img_webshop\/userimage-59e37de69475b.png"
    },
    {
        "role": "user",
        "id": "59dfc0cb07985",
        "email": "c@c.dk",
        "name": "C",
        "lastname": "C",
        "password": "3",
        "image": "img_webshop\/userimage-59dfc0cb06c5f.png"
    },
    {
        "role": "user",
        "id": "59dfc22f26f78",
        "phonenumber": "87654321",
        "name": "D",
        "lastname": "D",
        "password": "4",
        "image": "img_webshop\/userimage-59dfc22f2638d.png"
    },
    {
        "role": "user",
        "id": "59dfc460b261e",
        "email": "e@e.dk",
        "name": "E",
        "lastname": "E",
        "password": "5",
        "image": "img_webshop\/userimage-59dfc460af866.png"
    }
]

答案 2 :(得分:0)

一种选择是在ExceptionHandler中将内容类型显式添加到ResponseEntity。

控制器

@GetMapping("/path", produces = [MediaType.TEXT_XML_VALUE])

ControllerAdvice

@ExceptionHandler(org.springframework.validation.BindException::class)
    fun handleBindException(
        e: org.springframework.validation.BindException
    ): ResponseEntity<ErrorResponse> {    
        return ResponseEntity
            .status(HttpStatus.BAD_REQUEST)
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .body(ErrorResponse(e.message))
    }

ErrorResponse

data class ErrorResponse(val message: String?)

在Spring Boot 2.1.3上使用Kotlin进行测试