All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ec.gob.senescyt.sniese.commons.exceptions.mappers.DBConstraintViolationMapper Maven / Gradle / Ivy

There is a newer version: 2.0.5
Show newest version
package ec.gob.senescyt.sniese.commons.exceptions.mappers;

import ec.gob.senescyt.sniese.commons.core.Errores;
import ec.gob.senescyt.sniese.commons.core.MensajeError;
import org.eclipse.jetty.http.HttpStatus;
import org.hibernate.exception.ConstraintViolationException;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;

import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;

public class DBConstraintViolationMapper implements ExceptionMapper {

    //  Codigos de error de postgres: http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html
    public static final String FOREIGN_KEY_VIOLATION_SQL_CODE = "23503";
    public static final String MENSAJE_COMUN = "no es un valor v\u00E1lido";
    public static final String UNIQUE_CONSTRAINT_VIOLATION_SQL_CODE = "23505";

    @Override
    public Response toResponse(ConstraintViolationException exception) {
        if (FOREIGN_KEY_VIOLATION_SQL_CODE.equals(exception.getSQLState())) {
            String nombreCampo = exception.getConstraintName().replace("_fkey", "");
            String mensaje = String.format("%s %s", nombreCampo, MENSAJE_COMUN);
            return Response.status(BAD_REQUEST)
                    .entity(mensaje)
                    .build();
        }
        if (UNIQUE_CONSTRAINT_VIOLATION_SQL_CODE.equals(exception.getSQLState())) {
            Errores errores = new Errores();
            errores.agregar(new MensajeError("registroDuplicado", "El valor ya existe" ));
            return Response.status(HttpStatus.BAD_REQUEST_400).entity(errores).build();
        }
        return Response.status(INTERNAL_SERVER_ERROR)
                .entity(exception.getMessage())
                .build();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy