问题描述:

I am not able to inject EJBTransactionRolledbackException. I want to catch ConstraintViolationException. So first I need catch EJBTransactionRolledbackException then I can propagate to ConstraintViolationException exception using getCause().

How to inject it?

Below is my code.

 @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());

}

}

And my ApiErrors class is like below:

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);

}

}

相关阅读:
Top