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

pep1.commons.jpa.error.JpaHandlerExceptionAdvice Maven / Gradle / Ivy

/*
 * Copyright (C) 2016 Leonard Osang
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see .
 */

package pep1.commons.jpa.error;

import pep1.commons.domain.message.ErrorMessage;
import pep1.commons.domain.message.ValidationErrorMessage;
import pep1.commons.error.ErrorCodes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.persistence.EntityExistsException;
import javax.persistence.EntityNotFoundException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

@Slf4j
@ControllerAdvice
public class JpaHandlerExceptionAdvice {

    @ExceptionHandler(DataIntegrityViolationException.class)
    public ResponseEntity illegalArgument(DataIntegrityViolationException e) {
        log.error("Illegal argument: " + e.getLocalizedMessage());

        if (e.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {
            return validationFailed((org.hibernate.exception.ConstraintViolationException) e.getCause());
        }

        return new ResponseEntity<>(new ErrorMessage(
                HttpStatus.BAD_REQUEST,
                ErrorCodes.INVALID_INPUT,
                e.getLocalizedMessage()
        ), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(org.hibernate.exception.ConstraintViolationException.class)
    public ResponseEntity validationFailed(org.hibernate.exception.ConstraintViolationException e) {
        log.error("Constraint violation: " + e.getLocalizedMessage());

        ValidationErrorMessage message = new ValidationErrorMessage(
                HttpStatus.BAD_REQUEST,
                ErrorCodes.VALIDATION_FAILED,
                "Validation of sent resource failed. Please check input."
        );

        message.addError(e.getConstraintName(), null, e.getLocalizedMessage());

        return new ResponseEntity<>(message, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(TransactionSystemException.class)
    public ResponseEntity transactionFailed(TransactionSystemException e) {
        log.error("Constraint violation: " + e.getLocalizedMessage());

        if (e.getRootCause() instanceof ConstraintViolationException) {
            return validationFailed((ConstraintViolationException) e.getRootCause());
        }

        return new ResponseEntity<>(new ErrorMessage(
                HttpStatus.BAD_REQUEST,
                ErrorCodes.INVALID_INPUT,
                e.getLocalizedMessage()
        ), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity validationFailed(ConstraintViolationException e) {
        log.error("Constraint violation: " + e.getLocalizedMessage());

        ValidationErrorMessage message = new ValidationErrorMessage(
                HttpStatus.BAD_REQUEST,
                ErrorCodes.VALIDATION_FAILED,
                "Validation of sent resource failed. Please check input."
        );

        for (ConstraintViolation violation : e.getConstraintViolations()) {
            log.warn("Constraint violation: {}", violation.getMessage());
            message.addError(violation.getPropertyPath().toString(), violation.getLeafBean(), violation.getMessage());
        }

        return new ResponseEntity<>(message, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(BindException.class)
    public ResponseEntity validationFailed(BindException e) {
        log.error("Bind exception: " + e.getLocalizedMessage());

        return new ResponseEntity<>(new ErrorMessage(
                HttpStatus.BAD_REQUEST,
                ErrorCodes.INVALID_INPUT,
                e.getAllErrors().toString()
        ), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(PropertyReferenceException.class)
    public ResponseEntity wrongReference(PropertyReferenceException e) {
        log.error("Bind exception: " + e.getLocalizedMessage());

        return new ResponseEntity<>(new ErrorMessage(
                HttpStatus.BAD_REQUEST,
                ErrorCodes.INVALID_INPUT,
                e.getMessage()
        ), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(EntityNotFoundException.class)
    public ResponseEntity notFound(EntityNotFoundException e) {
        String message = (StringUtils.hasText(e.getLocalizedMessage()))
                ? e.getLocalizedMessage()
                : "The requested resource was not found.";
        log.error("Not Found Exception: " + message);

        return new ResponseEntity<>(new ErrorMessage(
                HttpStatus.NOT_FOUND,
                ErrorCodes.NOT_FOUND,
                message
        ), HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(EntityExistsException.class)
    public ResponseEntity existsAlready(EntityExistsException e) {
        String message = (StringUtils.hasText(e.getLocalizedMessage()))
                ? e.getLocalizedMessage()
                : "A resource with given parameters exists already";
        log.error("Not Found Exception: " + message);

        return new ResponseEntity<>(new ErrorMessage(
                HttpStatus.CONFLICT,
                ErrorCodes.EXISTS_ALREADY,
                message
        ), HttpStatus.CONFLICT);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy