vaadin 異常處理的方法

一、分兩個步驟:首先寫一個異常處理類,其次在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;

}

 

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章