-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: validate rest input using bean validation and add a mapper for …
…constraint violations
- Loading branch information
Showing
3 changed files
with
25 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
20 changes: 20 additions & 0 deletions
20
...rc/main/java/ch/mobi/itc/mobiliar/rest/exceptions/ConstraintViolationExceptionMapper.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package ch.mobi.itc.mobiliar.rest.exceptions; | ||
|
||
import javax.validation.ConstraintViolation; | ||
import javax.validation.ConstraintViolationException; | ||
import javax.ws.rs.core.Response; | ||
import javax.ws.rs.ext.ExceptionMapper; | ||
import java.util.stream.Collectors; | ||
|
||
public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> { | ||
|
||
@Override | ||
public Response toResponse(ConstraintViolationException e) { | ||
final String message = e.getConstraintViolations().stream() | ||
.map(ConstraintViolation::getMessage) | ||
.distinct() // since we use CDI and JAX-RS, there is potential that the validation kicks in twice. | ||
// calling distinct on the list of messages makes sure, that each message is included only once. | ||
.collect(Collectors.joining("\n")); | ||
return Response.status(Response.Status.BAD_REQUEST).entity(new ExceptionDto(message)).build(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters