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

时间:2015-08-03 15:39:49

标签: spring rest

我有这个存储库

@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代码?

1 个答案:

答案 0 :(得分:5)

您似乎需要将特定的异常映射到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
    }
}