英文:
message text not appearing in Spring Boot JSON REST error response
问题
这是您的翻译内容:
我已经按照mkyong和Bealdung的许多示例,但无法在Spring Boot中设置默认JSON错误响应的消息文本。
这是我的ControllerAdvice类
@ControllerAdvice
public class InventoryControllerAdviceExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(InventoryDuplicateException.class)
public void inventoryDuplicateHandle(HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.CONFLICT.value());
}
}
这是我的自定义异常类
public class InventoryDuplicateException extends RuntimeException {
public InventoryDuplicateException(Long id) {
super("库存项目 " + id + " 已存在!");
}
}
我使用Postman进行POST请求,内容如下
{
"id": "1",
"name": "orange"
}
当我抛出此异常时,我希望看到以下内容
{
"timestamp": "2020-06-29T04:37:48.023+00:00",
"status": 409,
"error": "Conflict",
"message": "库存项目 1 已存在!",
"path": "/path"
}
但我得到的是
{
"timestamp": "2020-06-29T04:37:48.023+00:00",
"status": 409,
"error": "Conflict",
"message": "",
"path": "/path"
}
我还尝试了显式传递文本
@ControllerAdvice
...
response.sendError(HttpStatus.CONFLICT.value(), "the message text");
...
这是我遵循的MKyong文章的引用
https://mkyong.com/spring-boot/spring-rest-error-handling-example/
感谢您的帮助。
英文:
I have followed many examples by mkyong and Bealdung but cant set the message text of the default JSON error response using Spring Boot.
Here's my ControllerAdvice class
@ControllerAdvice
public class InventoryControllerAdviceExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(InventoryDuplicateException.class)
public void inventoryDuplcateHandle(HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.CONFLICT.value());
}
}
And here's my customer exception class
public class InventoryDuplicateException extends RuntimeException {
public InventoryDuplicateException(Long id) {
super("Inventory item " + id + " exists already!");
}
}
Using postman I POST the following
{
"id": "1",
"name": "orange",
}
What I expect to see when I throw this exception is
{
"timestamp": "2020-06-29T04:37:48.023+00:00",
"status": 409,
"error": "Conflict",
"message": "Inventory item 1 exists already!",
"path": "/path"
}
but what I get is
{
"timestamp": "2020-06-29T04:37:48.023+00:00",
"status": 409,
"error": "Conflict",
"message": "",
"path": "/path"
}
I've also tried passing the text explicitly
@ControllerAdvice
...
response.sendError(HttpStatus.CONFLICT.value(), "the message text");
...
Here's the ref to the article from MKyong that I followed
https://mkyong.com/spring-boot/spring-rest-error-handling-example/
Thanks for your help.
专注分享java语言的经验与见解,让所有开发者获益!
评论