gpt4 book ai didi

spring - 如何使用 Spring Rest 和 PagingAndSortingRepository 返回 400 响应

转载 作者:行者123 更新时间:2023-12-02 08:20:24 27 4
gpt4 key购买 nike

我有这个存储库

@RepositoryRestResource(collectionResourceRel = "party_category", path = "party_category")
public interface PartyCategoryRepository extends PagingAndSortingRepository<PartyCategory, Integer>
{
}

当我尝试坚持时:

curl -X POST -H "Content-Type: application/json" http://localhost:8080/party_category -d "{\"description\":\"Mock description 3 modif\"}"

我收到 500 错误而不是 400:

{
"timestamp": 1438616019406,
"status": 500,
"error": "Internal Server Error",
"exception": "javax.validation.ConstraintViolationException",
"message": "Validation failed for classes[main.entity.party.PartyCategory] during persist time for groups [javax.validation.groups.Default, ]\\\nList of constraint violations:[\\\n\\\tConstraintViolationImpl{interpolatedMessage='no puede estar vacío', propertyPath=name, rootBeanClass=class main.entity.party.PartyCategory, messageTemplate='{org.hibernate.validator.constraints.NotBlank.message}'}\\\n]",
"path": "/party_category"
}

我该怎么做才能得到这样的友好回复?:

{
"field":"name",
"exception":"Field name cannot be null"
}

如何返回 400 http 代码?

最佳答案

看来您需要将特定异常映射到 HTTP 状态:

@Controller
public class ExceptionHandlingController {

// Convert a predefined exception to an HTTP Status code
@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Data integrity violation") // 409
@ExceptionHandler(javax.validation.ConstraintViolationException.class)
public void error() {
// Nothing to do
}
}

关于spring - 如何使用 Spring Rest 和 PagingAndSortingRepository 返回 400 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31791416/

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