io.crnk.jpa.internal.HibernateConstraintViolationExceptionMapper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of crnk-jpa Show documentation
Show all versions of crnk-jpa Show documentation
JSON API framework for Java
package io.crnk.jpa.internal;
import io.crnk.core.engine.document.ErrorData;
import io.crnk.core.engine.error.ErrorResponse;
import io.crnk.core.engine.error.ExceptionMapper;
import io.crnk.core.engine.http.HttpStatus;
import org.hibernate.exception.ConstraintViolationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HibernateConstraintViolationExceptionMapper implements ExceptionMapper {
private static final String META_TYPE_KEY = "type";
// assign ID do identity among different UNPROCESSABLE_ENTITY_422 results
private static final String HIBERNATE_CONSTRAINT_VIOLATION_EXCEPTION = "HibernateConstraintViolation";
@Override
public ErrorResponse toErrorResponse(ConstraintViolationException cve) {
HashMap meta = new HashMap<>();
meta.put(META_TYPE_KEY, HIBERNATE_CONSTRAINT_VIOLATION_EXCEPTION);
ErrorData error = ErrorData.builder()
.setMeta(meta)
.setStatus(Integer.toString(HttpStatus.UNPROCESSABLE_ENTITY_422))
.setCode(cve.getConstraintName()).setDetail(cve.getCause() != null ? cve.getCause().getMessage() : cve.getMessage())
.build();
return ErrorResponse.builder().setStatus(HttpStatus.UNPROCESSABLE_ENTITY_422).setSingleErrorData(error).build();
}
@Override
public ConstraintViolationException fromErrorResponse(ErrorResponse errorResponse) {
Iterable errors = errorResponse.getErrors();
ErrorData error = errors.iterator().next();
String msg = error.getDetail();
String constraintName = error.getCode();
return new ConstraintViolationException(msg, null, constraintName);
}
@Override
public boolean accepts(ErrorResponse errorResponse) {
if (errorResponse.getHttpStatus() != HttpStatus.UNPROCESSABLE_ENTITY_422) {
return false;
}
Iterable errors = errorResponse.getErrors();
Iterator iterator = errors.iterator();
if (!iterator.hasNext())
return false;
ErrorData errorData = iterator.next();
Map meta = errorData.getMeta();
return meta != null && HIBERNATE_CONSTRAINT_VIOLATION_EXCEPTION.equals(meta.get(META_TYPE_KEY));
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy