创建一个自定义服务层特定的运行时异常,其注释为@ApplicationException http://docs.oracle.com/javaee/7/api/javax/ejb/ApplicationException.html with 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 上),如下所示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>
作为一般提示,在 JSF 中,您还可以有一个全局异常处理程序,它只添加一个 faces 消息。当开始时这个启动示例 https://stackoverflow.com/questions/30464321/log-runtime-exceptions-using-log4j-in-jsf-web-application/30464553#30464553,你可以这样做YourExceptionHandler#handle()
method:
if (exception instanceof EntityAlreadyModifiedException) { // Unwrap if necessary.
// Add FATAL faces message and return.
}
else {
// Continue as usual.
}