Project

General

Profile

Download (2.51 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2018 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.vaadin.event.error;
10

    
11
import java.util.HashSet;
12
import java.util.Set;
13

    
14
import org.apache.log4j.Logger;
15

    
16
import com.vaadin.server.ErrorEvent;
17
import com.vaadin.server.ErrorHandler;
18
import com.vaadin.ui.Notification;
19

    
20
/**
21
 * Vaadin allows setting an com.vaadin.server.ErrorHandler for UIs and components.
22
 * The caveat with this built in approach is that there is only one {@link com.vaadin.server.ErrorHandler}
23
 * for any type of errors. This <code>DelegatingErrorHandler</code> allows registering handlers for specific types of errors.
24
 *
25
 * see https://dev.e-taxonomy.eu/redmine/issues/7241
26
 *
27
 * @author freimeier
28
 *
29
 */
30
public class DelegatingErrorHandler implements ErrorHandler{
31

    
32
    private static final long serialVersionUID = 3378605204517477112L;
33

    
34
    Set<ErrorTypeHandler<? extends Throwable>> handlers = new HashSet<>();
35

    
36
    public <E extends Throwable> void  registerHandler(ErrorTypeHandler<E> handler) {
37
        assert findHandler(handler.supports()) == null;
38
        handlers.add(handler);
39
    }
40

    
41
    @SuppressWarnings("unchecked")
42
    public <E extends Throwable> ErrorTypeHandler<E> findHandler(Class<E> errorClass){
43
        for(ErrorTypeHandler<?> h : handlers){
44
            if(h.supports().equals(errorClass)){
45
                return (ErrorTypeHandler<E>) h;
46
            }
47
        }
48
        return null;
49

    
50
    }
51

    
52
    /* (non-Javadoc)
53
     * @see com.vaadin.server.ErrorHandler#error(com.vaadin.server.ErrorEvent)
54
     */
55
    @Override
56
    public void error(ErrorEvent event) {
57

    
58
        boolean handlerFound = true;
59
        Throwable throwable = event.getThrowable();
60
        while(throwable != null){
61
            if(delegate(event, throwable)){
62
                break;
63
            }
64
            throwable = throwable.getCause();
65
        }
66
        if(!handlerFound){
67
            Notification.show(event.getThrowable().getMessage());
68
          }
69
    }
70

    
71
    private <E extends Throwable> boolean delegate(ErrorEvent event, E throwable){
72
        Class<E> errorClass = (Class<E>) throwable.getClass();
73
        Logger.getLogger(this.getClass()).debug(errorClass);
74
        ErrorTypeHandler<E> handler = findHandler(errorClass);
75
        if(handler != null){
76
            handler.handleError(event, throwable);
77
            return true;
78
        }
79
        return false;
80
    }
81
}
(1-1/4)