创建一个自定义服务层特定的运行时异常,使用@ApplicationException 和rollback=true 进行注释。
@ApplicationException(rollback=true)
public abstract class ServiceException extends RuntimeException {}
为一般业务异常创建一些具体的子类,例如约束冲突、必需的实体,当然还有乐观锁。
public class DuplicateEntityException extends ServiceException {}
public class EntityNotFoundException extends ServiceException {}
public class EntityAlreadyModifiedException extends ServiceException {}
有的可以直接扔。
public void register(User user) {
if (findByEmail(user.getEmail()) != null) {
throw new DuplicateEntityException();
}
// ...
}
public void addToOrder(OrderItem item, Long orderId) {
Order order = orderService.getById(orderId);
if (order == null) {
throw new EntityNotFoundException();
}
// ...
}
其中一些需要全局拦截器。
@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);
}
}
}
在ejb-jar.xml 中注册为默认拦截器(在所有 EJB 上)。
<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>
作为一般提示,在 JSF 中,您还可以有一个全局异常处理程序,它只添加一条面孔消息。当以this kickoff example 开头时,您可以在YourExceptionHandler#handle() 方法中执行类似的操作:
if (exception instanceof EntityAlreadyModifiedException) { // Unwrap if necessary.
// Add FATAL faces message and return.
}
else {
// Continue as usual.
}