我有一个表示JSON的String
:
[{"type":"ERROR","message":"some error message"}]
此String
由ex.contentUTF8()
在以下代码中返回:
@RestControllerAdvice
@RequiredArgsConstructor
public class ControllerExceptionHandler {
@ExceptionHandler(FeignException.class)
@ResponseBody
public String afterThrowing(FeignException ex, HttpServletResponse response) {
response.setStatus(ex.status());
return ex.contentUTF8();
}
}
HTTP客户端虽然没有得到JSON响应。相反,它获取的HTML的响应主体为String
。我该如何返回JSON?我需要反序列化String
吗?
更新
对客户端的响应必须完全是表示(将被序列化为)String
返回的ex.contentUTF8()
的JSON对象:
[{"type":"ERROR","message":"some error message"}]
因此,像ErrorDto
这样的包装对象(如一些答案中所述)将不起作用。
您应该返回适合您JSON表示形式的对象:
public class ErrorDto {
private String type;
private String message;
}
和:
@RestControllerAdvice
@RequiredArgsConstructor
public class ControllerExceptionHandler {
@ExceptionHandler(FeignException.class)
@ResponseBody
public ErrorDto afterThrowing(FeignException ex, HttpServletResponse response) {
return new ErrorDto("your type", "your message");
}
}
基于@Fabien的答案,您可以使用ResponseEntity<Object>
类来返回application/json
内容类型响应。使用ResponseEntity
本质上可以控制响应的每个方面。
您可以尝试这样的方法:
@ExceptionHandler(FeignException.class)
public ResponseEntity<Object> afterThrowing(FeignException ex) {
ErrorDto payload = new ErrorDto(ex.status(), ex.contenUTF8());
return ResponseEntity
.status(ex.status())
.contentType("application/json")
.body(payload);
}