Capture via ExceptionHandler


I'm trying to capture a javax.validation.ValidationException in my MB to play on an alert later. I tried with the three examples below independent but nothing returned. Should I enter any more code? I use version 2.5.0.

public class MeuMB extends AbstractEditPageBean<CTe, Long> {

public void tratar(RuntimeException ex) {
    System.out.println("1111" + ex);

public void tratar2(ValidationException ex) {
    System.out.println("2222" + ex);

public void tratar3(Exception ex) {
    System.out.println("3333" + ex);

The class has @ViewController and in it already calls the @Controller.

My calling method is as follows:

public String upload() {
    //int i = 5 / 0;

    try {
    } catch (Exception ex) {  
        getMessageContext().add(getResourceBundle().getString("cte.msg.uploadFail"), SeverityType.ERROR);
        return null;

If I take the comment "5/0," an error occurs and is called the RuntimeException. So calls and imports would be ok.

Problem is that in the "generate" method I force null in a not null field. Just to test.

@JoinColumn(name = "municipio_id", referencedColumnName = "id")
@ManyToOne(optional = false)
private Municipio municipio;

And this error I am not able to capture neither in the try catch nor by the calls ExceptionHandler.

asked by anonymous 22.12.2015 / 13:26

2 answers


Validation triggers a ConstraintViolationException that can be encapsulated in TransactionException .

So I opted for the following solution:

public void tratarErroInesperado(RuntimeException e) throws IOException {
    if (tratarConstraintViolationException(e)) {
    } else {

private boolean tratarConstraintViolationException(Exception e) {
    Throwable cause = e;
    while (cause != null) {
        if (cause instanceof ConstraintViolationException) {
            for (ConstraintViolation<?> violation : cve.getConstraintViolations()) {
                messageContext.add(violation.getMessage(), SeverityType.ERROR);
            return true;
        cause = cause.equals(cause.getCause()) ? null : cause.getCause();
    return false;
11.10.2016 / 21:57

According to the documentation, these methods will only be invoked if the exception occurs in some other method, in this case of the class MyMB, to test it is necessary to create another method and cause the exception.

public class Simples {

    public void tratador(NullPointerException cause) { }

    public void tratador(AbacaxiException cause) { }    

    public void inserir() { }   

    public void alterar() { }   

    public void excluir() { }   

If the NullPointerException or AbacaxiException exceptions occur in the   methods of the Simple class, the treatment will be delegated to your   handler.


22.12.2015 / 14:46