有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在用例清理体系结构中处理来自网关实现的错误

当我们使用洋葱架构构建软件时,如何处理来自网关实现的异常

为了澄清,我使用Java和SpringBoot创建了一个示例:

@Component
@AllArgsConstructor
public class SaveAddressUseCase{
    private final GetCustomerGateway getCustomerGateway;

    public void execute(AddressDomain address, Long customerId){
        try{
            //validates the customerId supplied and returns the customer from an external service.
            CustomerDomain customer = getCustomerGateway.execute(customerId);
            address.setCustomer(customer);
            //saves the address
        }catch(CustomerNotFoundException ex) {
            AddressErrorDomain addressErrorDomain = new AddressErrorDomain();
            //saves the address in a error table with httpStatus 404
        } catch (InternalErrorException ex) {
            AddressErrorDomain addressErrorDomain = new AddressErrorDomain();
            //save the address in a error table with httpStatus 500
        }
    }
}

这是一个简单的用例,将保存一个地址,但首先,它需要从外部服务获取该地址的客户。如果找不到客户,我需要将地址保存在错误表中,以便以后处理。如果这个外部服务关闭,情况也是如此,但是区分这两个错误很重要,我可以使用API调用返回的HttpStatus来处理这个问题

public interface GetCustomerGateway {
   CustomerDomain execute(Long customerId);
}

@Component
@AllArgsConstructor
public class GetCustomerGatewayImpl implements GetCustomerGateway {
    private final CustomerApi customerApi; //Feign interface to call an external service

    public CustomerDomain execute(Long customerId){
        try{
            return customerApi.getCustomerById(customerId);
        }catch(FeignException ex){
            if (ex.status() == HttpStatus.NOT_FOUND.value()) {
                throw new CustomerNotFoundException();
            } else {
                throw new InternalErrorException();
            }
        }
    }
}

最后,这是我的网关实现,它只是使用一个简单的假接口调用这个外部服务,并抛出两个自定义异常,我从RuntimeException扩展了这两个自定义异常

问题:在用例中捕获这两个异常我没有处理只有网关必须知道的细节?或者更糟糕的是,我没有使用异常来控制我的应用程序的流程?如何以比我在示例中更好的方式处理来自网关实现的错误

Obs:在本例中,在错误表中保存地址很重要,以免破坏客户端的用户体验,我还需要区分这些错误

提前谢谢


共 (0) 个答案