Use mappers for errors

This commit is contained in:
René Pfeuffer
2018-10-26 14:20:19 +02:00
parent cd0964d850
commit 9279bfca5f
9 changed files with 151 additions and 90 deletions

View File

@@ -1,21 +1,13 @@
package sonia.scm.api.rest;
import sonia.scm.AlreadyExistsException;
import sonia.scm.api.v2.resources.ErrorDto;
import sonia.scm.web.VndMediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class AlreadyExistsExceptionMapper implements ExceptionMapper<AlreadyExistsException> {
@Override
public Response toResponse(AlreadyExistsException exception) {
return Response.status(Status.CONFLICT)
.entity(ErrorDto.from(exception))
.type(VndMediaType.ERROR_TYPE)
.build();
public class AlreadyExistsExceptionMapper extends ContextualExceptionMapper<AlreadyExistsException> {
public AlreadyExistsExceptionMapper() {
super(AlreadyExistsException.class, Status.CONFLICT);
}
}

View File

@@ -1,17 +1,13 @@
package sonia.scm.api.rest;
import sonia.scm.ConcurrentModificationException;
import sonia.scm.api.v2.resources.ErrorDto;
import sonia.scm.web.VndMediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class ConcurrentModificationExceptionMapper implements ExceptionMapper<ConcurrentModificationException> {
@Override
public Response toResponse(ConcurrentModificationException exception) {
return Response.status(Response.Status.CONFLICT).entity(ErrorDto.from(exception)).type(VndMediaType.ERROR_TYPE).build();
public class ConcurrentModificationExceptionMapper extends ContextualExceptionMapper<ConcurrentModificationException> {
public ConcurrentModificationExceptionMapper() {
super(ConcurrentModificationException.class, Response.Status.CONFLICT);
}
}

View File

@@ -0,0 +1,36 @@
package sonia.scm.api.rest;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.ExceptionWithContext;
import sonia.scm.api.v2.resources.ExceptionWithContextToErrorDtoMapper;
import sonia.scm.web.VndMediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
public class ContextualExceptionMapper<E extends Throwable & ExceptionWithContext> implements ExceptionMapper<E> {
@Inject
private ExceptionWithContextToErrorDtoMapper mapper;
private static final Logger logger = LoggerFactory.getLogger(ContextualExceptionMapper.class);
private final Response.Status status;
private final Class<E> type;
public ContextualExceptionMapper(Class<E> type, Response.Status status) {
this.type = type;
this.status = status;
}
@Override
public Response toResponse(E exception) {
logger.debug("map {} to status code {}", type.getSimpleName(), status.getStatusCode());
return Response.status(status)
.entity(mapper.map(exception))
.type(VndMediaType.ERROR_TYPE)
.build();
}
}