gpt4 book ai didi

spring-boot - 发生 HttpMessageNotReadableException 时获取缺失字段

转载 作者:行者123 更新时间:2023-12-03 08:38:44 25 4
gpt4 key购买 nike

我有一个 API,需要以下 dto 结构。

data class SignupRequest(
@NotEmpty(message ="Username must not be empty")
@NotNull(message = "Username must not be null")
val username: String,

@NotEmpty(message ="Password must not be empty")
@NotNull(message = "Password must not be null")
val password: String,

@NotEmpty(message ="Email must not be empty")
@NotNull(message = "Email must not be null")
val email: String
)

下面是 Controller

@RestController
class AuthenticationController {
@Autowired
private lateinit var userRepository: UserRepository

@PostMapping("/signup")
@ResponseStatus(HttpStatus.CREATED)
fun signup(@Valid @RequestBody request: SignupRequest) : SignupResponse {
val user = User(
id = UUID.randomUUID(),
username = request.username,
password = request.password,
email = request.email
)

try {
userRepository.save(user)
return SignupResponse(msg = "Success");
} catch (e: Exception) {
throw ResponseStatusException(HttpStatus.BAD_GATEWAY, "Invalid fields", e)
}
}
}

当我进行 API 调用时,如果任何一个字段丢失或为 null,我会收到 HttpMessageNotReadableException,并且因为默认错误消息对我尝试格式化的客户端来说没有多大意义它通过为该异常提供错误处理程序来实现。

@RestControllerAdvice
class ApiExceptionHandler {

@ExceptionHandler(HttpMessageNotReadableException::class)
fun handleMessageNotReadableException(
ex: HttpMessageNotReadableException,
req: HttpServletRequest,
res: HttpServletResponse
) : ResponseEntity<ApiError> {
val error = ApiError();
return ResponseEntity<ApiError>(error, HttpStatus.BAD_REQUEST)
}

}

但是,我还需要知道缺少的确切字段,虽然默认错误消息包含此信息,但异常对象没有它,我也无法扩展 ResponseEntityExceptionHandler ,因为这样我必须为其处理的所有默认情况提供实现。

如何轻松正确地返回 API 调用中缺少的字段

最佳答案

查看 HttpMessageNotReadableException.getCause() 是否有用。根据您的底层 JSON 库,它可能会为您提供您想要的内容。在 Jackson JSON 解析中,我发现一些 Jackson 特有的异常确实具有字段级信息。

例如,

        Throwable cause = e.getCause();

if (cause instanceof JsonParseException) {
JsonParseException jpe = (JsonParseException) cause;
msg = jpe.getOriginalMessage();
}

Jackson Javadoc .

我对此进行了一些讨论in a Blog post .

关于spring-boot - 发生 HttpMessageNotReadableException 时获取缺失字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63219682/

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