gpt4 book ai didi

json - 如何处理 Spring Rest Web Service 中的 JSON 解析错误

转载 作者:行者123 更新时间:2023-12-03 16:43:29 24 4
gpt4 key购买 nike

我有一个用 Spring Boot 开发的休息 Web 服务。我能够处理由于我的代码而发生的所有异常,但假设客户端发布的 json 对象与我想要反序列化的对象不兼容,我得到

"timestamp": 1498834369591,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Can not deserialize value

我想知道有没有办法针对此异常,我可以为客户端提供自定义异常消息。我不知道如何处理这个错误。

最佳答案

要为每个 Controller 自定义此消息,请使用 @ExceptionHandler 的组合和 @ResponseStatus在您的 Controller 中:

    @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "CUSTOM MESSAGE HERE")
@ExceptionHandler(HttpMessageNotReadableException.class)
public void handleException() {
//Handle Exception Here...
}

如果您宁愿定义一次并全局处理这些异常,那么使用 @ControllerAdvice类(class):
@ControllerAdvice
public class CustomControllerAdvice {
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "CUSTOM MESSAGE HERE")
@ExceptionHandler(HttpMessageNotReadableException.class)
public void handleException() {
//Handle Exception Here...
}
}

关于json - 如何处理 Spring Rest Web Service 中的 JSON 解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44850637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com