Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Return a 400 response with Spring Rest and PagingAndSortingRepository

Tags:

rest

spring

I have this repository

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

When I try to persist with:

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

I get a 500 Error instead a 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"
}

What can I do to get a friendly response like this?:

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

How can I return a 400 http code?

like image 299
José Vte. Calderón Avatar asked Feb 09 '23 09:02

José Vte. Calderón


1 Answers

It seems you need to map your specific Exception to the HTTP Status:

@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
    }
}
like image 168
morsor Avatar answered Feb 13 '23 22:02

morsor