一、分两个步骤:首先写一个异常处理类,其次在UI的init方法内加入一句: UI.getCurrent().setErrorHandler(new CustomErrorHandler());即可;
异常类如下:
import java.sql.SQLException;
import org.apache.ibatis.exceptions.PersistenceException;
import com.vaadin.data.fieldgroup.FieldGroup;
import com.vaadin.server.AbstractErrorMessage;
import com.vaadin.server.DefaultErrorHandler;
import com.vaadin.server.ErrorEvent;
import com.vaadin.server.ErrorHandler;
import com.vaadin.server.ErrorMessage;
import com.vaadin.server.Page;
import com.vaadin.server.UserError;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;
public class CustomErrorHandler implements ErrorHandler {
@Override
public void error(ErrorEvent event) {
// TODO Auto-generated method stub
// Finds the original source of the error/exception
AbstractComponent component = DefaultErrorHandler.findAbstractComponent(event);
if (component != null) {
ErrorMessage errorMessage = getErrorMessageForException(event.getThrowable());
if (errorMessage != null) {
component.setComponentError(errorMessage);
new Notification(null, errorMessage.getFormattedHtmlMessage(), Type.WARNING_MESSAGE, true)
.show(Page.getCurrent());
return;
}
}
DefaultErrorHandler.doDefault(event);
}
private static ErrorMessage getErrorMessageForException(Throwable t) {
PersistenceException persistenceException = getCauseOfType(t, PersistenceException.class);
if (persistenceException != null) {
return new UserError(persistenceException.getLocalizedMessage(), AbstractErrorMessage.ContentMode.TEXT, ErrorMessage.ErrorLevel.ERROR);
}
// 获取自定义异常类型,根据不同的类型抛出不同的信息给用户;
/* SQLException sqlException = getCauseOfType(t, SQLException.class);
if (sqlException != null) {
return new SQLErrorMessage(sqlException);
}
FieldGroup.CommitException commitException = getCauseOfType(t, FieldGroup.CommitException.class);
if (commitException != null) {
return new CommitErrorMessage(commitException);
}
EJBException eJBException = getCauseOfType(t, EJBException.class);
if (eJBException != null) {
return new UserError(eJBException.getLocalizedMessage(), AbstractErrorMessage.ContentMode.TEXT, ErrorMessage.ErrorLevel.ERROR);
}*/
}
private static <T extends Throwable> T getCauseOfType(Throwable th, Class<T> type) {
while (th != null) {
if (type.isAssignableFrom(th.getClass())) {
return (T) th;
} else {
th = th.getCause();
}
}
return null;
}
}