无法注入EJBTransactionRolledbackException

时间:2016-07-23 17:28:43

标签: spring java-ee exception-handling ejb bean-validation

我无法注射EJBTransactionRolledbackException。我想抓住ConstraintViolationException。首先,我需要捕获EJBTransactionRolledbackException然后我可以使用ConstraintViolationException传播到getCause()异常。 如何注射?

以下是我的代码。

 @ControllerAdvice
 public class RestExceptionProcessor extends            ResponseEntityExceptionHandler {
// Here I am not able to inject EJBTransactionRolledbackException.
@ExceptionHandler({EJBTransactionRolledbackException.class})
protected ResponseEntity<Object> handleUniqueKeyViolation(EJBTransactionRolledbackException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    Throwable t = ex.getCause();

    if(t != null &(t instanceof RollbackException)){

        if(t != null &(t instanceof ConstraintViolationException)) {
            return handleConstraintViolation((ConstraintViolationException) ex.getCause(), headers, status, request);
        }

        return handleConstraintViolation((RollbackException) ex.getCause(), headers, status, request);
    }

    String error = ex.getLocalizedMessage() + " " + ex.getMessage();
    ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}

@ExceptionHandler({RollbackException.class})
protected ResponseEntity<Object> handleConstraintViolation(RollbackException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    String error = ex.getLocalizedMessage() + " " + ex.getMessage();
    ApiError apiError = new ApiError(HttpStatus.CONFLICT, ex.getLocalizedMessage(), error);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}

@ExceptionHandler({ConstraintViolationException.class})
protected ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    List<String> errors = new ArrayList<String>();
    for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
        errors.add(violation.getRootBeanClass().getName() + " " + 
          violation.getPropertyPath() + ": " + violation.getMessage());
    }
    ApiError apiError = new ApiError(HttpStatus.CONFLICT, ex.getLocalizedMessage(), error);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
    }
}

我的ApiErrors课程如下:

public class ApiError {

private HttpStatus status;
private String message;
private List<String> errors;

public ApiError(HttpStatus status, String message, List<String> errors) {
    super();
    this.status = status;
    this.message = message;
    this.errors = errors;
}

public ApiError(HttpStatus status, String message, String error) {
    super();
    this.status = status;
    this.message = message;
    this.errors = Arrays.asList(error);
    }
}

0 个答案:

没有答案