让表示层(JSF)处理来自服务层(EJB)的业务异常

Tin*_*iny 3 jsf ejb exception-handling java-ee optimistic-locking

更新提供的实体的EJB方法(使用CMT):

@Override
@SuppressWarnings("unchecked")
public boolean update(Entity entity) throws OptimisticLockException {
    // Code to merge the entity.
    return true;
}
Run Code Online (Sandbox Code Playgroud)

javax.persistence.OptimisticLockException如果检测到并发更新,则将抛出,这将由调用者(托管bean)精确处理.

public void onRowEdit(RowEditEvent event) {
    try {
        service.update((Entity) event.getObject())
    } catch(OptimisticLockException e) {
        // Add a user-friendly faces message.
    }
}
Run Code Online (Sandbox Code Playgroud)

但这样做会使javax.persistence表达层上的API 产生额外的依赖性,这是一种导致紧密耦合的设计气味.

应该包装哪个例外,以便完全省略紧耦合问题?或者是否有一种标准方法来处理此异常,这反过来又不会导致在表示层上强制执行任何服务层依赖性?

顺便说一句,我发现在EJB中(在服务层本身上)捕获此异常然后向客户端(JSF)返回一个标志值是笨拙的.

Bal*_*usC 7

创建使用@ApplicationExceptionwith 注释的自定义服务层特定运行时异常rollback=true.

@ApplicationException(rollback=true)
public abstract class ServiceException extends RuntimeException {}
Run Code Online (Sandbox Code Playgroud)

为一般业务异常创建一些具体的子类,例如约束违规,必需实体,当然还有乐观锁.

public class DuplicateEntityException extends ServiceException {}
Run Code Online (Sandbox Code Playgroud)
public class EntityNotFoundException extends ServiceException {}
Run Code Online (Sandbox Code Playgroud)
public class EntityAlreadyModifiedException extends ServiceException {}
Run Code Online (Sandbox Code Playgroud)

其中一些可以直接抛出.

public void register(User user) {
    if (findByEmail(user.getEmail()) != null) {
        throw new DuplicateEntityException();
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)
public void addToOrder(OrderItem item, Long orderId) {
    Order order = orderService.getById(orderId);

    if (order == null) {
        throw new EntityNotFoundException();
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

其中一些需要全局拦截器.

@Interceptor
public class ExceptionInterceptor implements Serializable {

    @AroundInvoke
    public Object handle(InvocationContext context) throws Exception {
        try {
            return context.proceed();
        }
        catch (javax.persistence.EntityNotFoundException e) { // Can be thrown by Query#getSingleResult().
            throw new EntityNotFoundException(e);
        }
        catch (OptimisticLockException e) {
            throw new EntityAlreadyModifiedException(e);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

其中注册为默认拦截器(在所有EJB上),如下所示ejb-jar.xml.

<interceptors>
    <interceptor>
        <interceptor-class>com.example.service.ExceptionInterceptor</interceptor-class>
    </interceptor>
</interceptors>
<assembly-descriptor>
    <interceptor-binding>
        <ejb-name>*</ejb-name>
        <interceptor-class>com.example.service.ExceptionInterceptor</interceptor-class>
    </interceptor-binding>
</assembly-descriptor>
Run Code Online (Sandbox Code Playgroud)

作为一般提示,在JSF中,您还可以拥有一个全局异常处理程序,它只添加一个faces消息.从这个启动示例开始,您可以在YourExceptionHandler#handle()方法中执行以下操作:

if (exception instanceof EntityAlreadyModifiedException) { // Unwrap if necessary.
    // Add FATAL faces message and return.
}
else {
    // Continue as usual.
}
Run Code Online (Sandbox Code Playgroud)