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;

}

 

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值