8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

Java,如何从 UI 调用 Rest API 时返回不同的状态代码 400、404、500、200?

Abrar Rofique 1月前

16 0

我正在从 Ui 调用 RestAPI。RestAPI 然后调用 Soap API。我进行了 rest 和 soap 之间的映射。问题是,在调用 REST API 时如何将状态代码/状态消息返回到 UI。如果...

我正在从 Ui 调用 RestAPI。RestAPI 然后调用 Soap API。我进行了 rest 和 soap 之间的映射。问题是在调用 REST API 时如何将状态代码/状态消息返回到 UI。

  1. 如果输入值错误,Soap 请求将返回错误代码。如何从 Soap(AckConfirmSoapClient)向其他控制器(AcknowledgementController)返回 400?
  2. 如果 Soap API 发生故障,如何从 Soap(AckConfirmSoapClient)返回 500 到其他控制器(AcknowledgementController)?
  3. 如果出现任何其他问题,如何返回 500 内部服务器错误?
  4. 如果一切正常,则返回 http 状态代码是否正常?如果一切正常,我的代码工作正常,rest api 返回状态代码正常。请帮忙在 Rest 控制器或 SoapClient 类中哪里进行更改以捕获异常并返回状态代码 400、404 和 500。谢谢
//AcknowledgementController.java. Calling RestAPI from UI
public class AcknowledgementController {

    @Autowired
    AckConfirmSoapClient eConfirmSoapClient;

  
    public AcknowledgementController(){
      super();
    }
  
    @PostMapping("/acknowledgement")
    public ResponseEntity<EConfirmResponse> postConfirmation(@Valid @RequestBody EConfirmRequest
                                                                        eConfirmRequest) throws InterruptedException
        {
        try
        {
        EConfirmResponse eConfirmResponse = eConfirmSoapClient.callConfirm(eConfirmRequest);
        return new ResponseEntity<>(eConfirmResponse, HttpStatus.OK);
        }
      catch (WebServiceException ex) {
        if (eConfirmResponse != null && eConfirmResponse.getSystemErrors() != null && eConfirmResponse.getSystemErrors().size() > 0) {
          return ResponseEntity.status(500).body(eConfirmResponse);
        }
        else
        {
          return new ResponseEntity<>(eConfirmResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }
      }
     }
  
  }
______________________________
//AckConfirmSoapClient. Calling SOAP API, return fault code in response in case of bad request 
@Service
public class AckConfirmSoapClient {
  @Value("${eConfirm.url}")
  private String eConformUrl;

  @Autowired
  @Qualifier("eConfirmWebServiceTemplate")
  private WebServiceTemplate eConfirmWebServiceTemplate;

  public EConfirmResponse callConfirm(EConfirmRequest eConfirmRequest) {
    EConfirmResponse eConfirmResponse = new EConfirmResponse();
    EConfirmResponseType eConfirmResponseType = null;

    EConfirmRequestType eConfirmRequestType = EConfirmRequestMapper.mapRequestFromRestToSoap(eConfirmRequest);
    WFContextType contextType = buildWfContext(eConfirmRequest);
    try
    {
      eConfirmResponseType = marshaleConfirm(eConfirmRequestType, contextType);

      if(eConfirmResponseType.getWFFaultList() == null) {
        eConfirmResponse = eConfirmResponseMapper.mapResponseFromSoapToRest(eConfirmResponseType);
      }
      else
      {
        throw new CommonWebClientException(APP_ID_QF, null, null, null);
      }
    }
    catch (SoapFaultClientException | WebServiceIOException | CommonWebClientException exp)
    {
      if (eConfirmResponseType.getWFFaultList() != null) {
        eConfirmResponse = eConfirmResponseMapper.mapeConfirmErrorResponse(eConfirmResponseType);
       } else {
        throw new CommonWebClientException(APP_ID_QF, exp, null, null);
      }
   }
   return eConfirmResponse;


  }
  public eConfirmResponseType marshaleConfirm(eConfirmRequestType eConfirmRequestType, WFContextType contextType) throws CommonWebClientException {
    String response = Constants.EMPTY;
    ObjectMapper mapper = new ObjectMapper();
    eConfirmResponseType eConfirmResponseType = null;

    //Get the response payload
    JAXBElement<eConfirmResponseType> jaxbResponsePayload = getResponsePayload(eConfirmRequestType, contextType);

    //Convert the response payload to string 
    try {
      response = mapper.writeValueAsString(jaxbResponsePayload);
    } catch (JsonProcessingException e) {
      log.error("JsonProcessingException: ", e);
    }
    eConfirmResponseType = jaxbResponsePayload.getValue();

    return eConfirmResponseType;
  }
  private JAXBElement<eConfirmResponseType> getResponsePayload(eConfirmRequestType eConfirmRequestType, WFContextType contextType) throws CommonWebClientException {
      ObjectFactory eDeliveryConfirm = new ObjectFactory();

      JAXBElement<eConfirmRequestType> jaxbeConfirmRequestType = eDeliveryConfirm.createEConfirmRequest(eConfirmRequestType);
    try {
    } catch (JAXBException e) {
      log.error("JAXBException while JAXBUtil request marshalToXml: " + e);
    }

     //marshalSendAndReceive returns plain object (not JAXBElement)
    Object response = eConfirmWebServiceTemplate.marshalSendAndReceive(eConformUrl, jaxbeConfirmRequestType,
          getWebServiceMessageCallback(contextType));
    ObjectMapper objectMapper = new ObjectMapper();

    try {
          LOGGER.info("mapped and marshalledToXml request payload for eConfirm SOAP call: " + objectMapper.writeValueAsString(response));
      } catch (JsonProcessingException e) {
          LOGGER.error("xml marshalling exception while calling JAXBUtil: ", e);
      }

      return  (JAXBElement<eConfirmResponseType>) response;
  }

  private WebServiceMessageCallback getWebServiceMessageCallback(WFContextType context) {
    log.debug("Started getWebServiceMessageCallback");

    return message -> {
      SaajSoapMessage soapMessage = (SaajSoapMessage) message;
      soapMessage.setSoapAction(IntegrationConstants.SOAP_ACTION_EIEP_EDELIVERY_CONFIRM);
      SoapHeader soapHeader = soapMessage.getSoapHeader();
      // create a marshaller
      try {
        setHeader(soapHeader, context);
      } catch (JAXBException e) {
        log.error("JAXBException while getWebServiceMessageCallback: " + e);
      }

      try {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        message.writeTo(byteArrayOutputStream);
        byteArrayOutputStream.close();
      } catch (IOException ex) {
        log.error("IOException while getWebServiceMessageCallback: " + ex);
      }
    };
  }
  private void setHeader(SoapHeader soapHeader, WFContextType wfContext) throws JAXBException, WebServiceException {

    try {
      JAXBContext context = JAXBContext.newInstance(WFContextType.class);
      Marshaller marshaller = context.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

      JAXBElement<WFContextType> jaxbElementWFContext =
        new JAXBElement<>(new QName(IntegrationConstants.QNAME_EIEP_MESSAGE_2007, IntegrationConstants.WF_CONTEXT_LOCAL_PART), WFContextType.class, wfContext);
      log.info("mapped and marshalledToXml request headers to eConfirm SOAP call: " + JAXBUtil.marshalToXml(jaxbElementWFContext));
      marshaller.marshal(jaxbElementWFContext, soapHeader.getResult());
    }
    catch (WebServiceException | JAXBException ex) {
      log.error("IOException while getWebServiceMessageCallback: " + ex);
    }
  }
  public WFContextType buildWfContext(EConfirmRequest eConfirmRequest) {
    WFContextType wfContext = new WFContextType();

    // unique id per message
    String hostname = null;
    try
    {
      hostname = getHostname();
    }
    catch (UnknownHostException e) {
      LOGGER.error("UnknownHostException while buildWfContext: " + e);
    }
    wfContext.setMessageId(hostname + Constants.COLON + new UID());

    // unique id per set of requests
    SessionType session = new SessionType();
    if (eConfirmRequest != null) {
      session.setSessionId(eConfirmRequest.getContext().getSessionId());

      // ID of the application creating the message
      wfContext.setApplicationId(eConfirmRequest.getContext().getAplicationId());
     
    }

    // step count within the "session".  first message must be 1.
    session.setSessionSequenceNumber(Constants.STRING_ONE);
    wfContext.setSession(session);

    wfContext.setCreationTimestamp(getCreationTimestamp());

    wfContext.setHostName(hostname);

    // identifies the server, instance, or queue of the message creator
    wfContext.setInvokerId(wfContext.getHostName());

    return wfContext;
  }
  private static String getHostname() throws UnknownHostException {
    return InetAddress.getLocalHost().getHostName();
  }
  private XMLGregorianCalendar getCreationTimestamp() {
    XMLGregorianCalendar creationTimestamp = null;
    try {
      creationTimestamp = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
    } catch (DatatypeConfigurationException e) {
 e);
    }
    return creationTimestamp;
  }
}
------------------------------------------------------------______________
//mapping response soap to rest
public class EConfirmResponseMapper {

    private EConfirmResponseMapper() {
      super();
    }
    public static EConfirmResponse mapResponseFromSoapToRest(EConfirmResponseType eConfirmResponseSoap) {
        EConfirmResponse eConfirmResponse = new EConfirmResponse();
      if(eConfirmResponseSoap == null){
        return null;
      }
      eConfirmResponse.setUuid(eConfirmResponseSoap.getUUID());
        
      return eConfirmResponse;
    }
  
    public static eConfirmResponse mapeConfirmErrorResponse(eConfirmResponseType eConfirmResponseSoap) throws CommonException {
      eConfirmResponse eConfirmResponse = new eConfirmResponse();
      if(eConfirmResponseSoap == null){
        return null;
      }
      List<SystemError> eConfirmResponseSystemError = new ArrayList<>();
      SystemError systemError = new SystemError();
  
      if (eConfirmResponseSoap != null && eConfirmResponseSoap.getWFFaultList() != null) {
        for (WFFaultType eiepSoapFaultList : eConfirmResponseSoap.getWFFaultList().getWFFault()) {
          systemError.setCreatorApplicationId(Constants.APP_ID_QF);
          systemError.setCode(eiepSoapFaultList.getSeverity().value());
          systemError.setSubCode(Constants.EIEP_ERROR_CODE);
          systemError.setMessage("FaultCode :" + eiepSoapFaultList.getFaultCode() + "," + Constants.SPACE +
            eiepSoapFaultList.getFaultReasonText() + Constants.SPACE + eiepSoapFaultList.getTechnicalText());
          eConfirmResponseSystemError.add(systemError);
        }
        eConfirmResponse.setSystemErrors(eConfirmResponseSystemError);
      }
      return eConfirmResponse;
    }
  }
   

帖子版权声明 1、本帖标题:Java,如何从 UI 调用 Rest API 时返回不同的状态代码 400、404、500、200?
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由Abrar Rofique在本站《spring-boot》版块原创发布, 转载请注明出处!
最新回复 (0)
返回
作者最近主题: