[英]Why I cannot send proper Server status as response and instead I get a "no response" when I hit my endpoint?
I was testing an endpoint that is supposed to return a JSON.我正在测试一个应该返回 JSON 的端点。
Works great.效果很好。 But when there is an exception (like a forbidden) it should return a proper error code and message.
但是当出现异常(如禁止)时,它应该返回正确的错误代码和消息。
Right now im doing it like this:现在我这样做:
@ResponseBody
@GetMapping(produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity getInfo() {
try{
//..do something
}catch(Exception e){
return new ResponseEntity<>("Error calculating the required information", null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Instead when I curl the url or with swagger I get this:相反,当我卷曲 url 或大摇大摆地时,我得到了这个:
Request URL
http://localhost:8081/info
Request Headers
{
"Accept": "application/json;charset=UTF-8"
}
Response Body
no content
Response Code
0
Response Headers
{
"error": "no response from server"
}
And yes, I am hitting the endpoint (I debugged it).是的,我正在击中端点(我调试了它)。
Any idea why this response is returning?知道为什么这个响应会返回吗? Thanks.
谢谢。
You need change method sign您需要更改方法标志
public ResponseEntity<Void> getInfo() {
and also change return type with并更改返回类型
return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
If you want return a specific message you need to create custom exception class.如果要返回特定消息,则需要创建自定义异常类。
You can find an example the following project link on github : https://github.com/in28minutes/spring-microservices/tree/master/02.restful-web-services/src/main/java/com/in28minutes/rest/webservices/restfulwebservices您可以在 github 上找到以下项目链接的示例: https : //github.com/in28minutes/spring-microservices/tree/master/02.restful-web-services/src/main/java/com/in28minutes/rest/网络服务/restful网络服务
You can change your code like this您可以像这样更改代码
@ResponseBody
@GetMapping(produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<String> getInfo() {
try {
//..do something
} catch(Exception e) {
return new ResponseEntity<>("Error calculating the required information", null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Definition of ResponseEntity code is like this. ResponseEntity 代码的定义是这样的。
public ResponseEntity(T body, MultiValueMap<String, String> headers, HttpStatus status)
You have to match generic type.你必须匹配泛型类型。
One thing interesting is I made same code you attached, and it worked well.有趣的一件事是我制作了您附加的相同代码,并且运行良好。 (returned 500 error with response body)
(响应正文返回 500 错误)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.