有 Java 编程相关的问题?

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

阿里云Java捕获和提升事件中的错误处理

我对Java和学习曲线都是新手。我在阿里云集成中创建了一个java函数计算

我需要连接到密钥管理服务(KMS)以获取机密。如果KMS不可用或无法按功能连接,则我需要在MNS中的主题中创建事件消息。我想知道如何处理这个错误

下面是代码片段

public class SFTP14 implements StreamRequestHandler, FunctionInitializer {

    public void initialize(Context context) throws IOException {
    }


    public void handleRequest( InputStream inputStream
                             , OutputStream outputStream
                             , Context context) throws IOException 
    {
       
       // Get values from Environment varaible of function
       String bucketname = System.getenv("BUCKET_NAME");
       String endpoint = System.getenv("ENDPOINT");
       String kmssecret = System.getenv("KMSSECRET");
       String MNSEndpoint="http://mns.cn-shanghai.aliyuncs.com/";
      
       outputStream.write(new String("Bucket Name:"+bucketname +" \n").getBytes());
       outputStream.write(new String("End Point Name:"+endpoint +" \n").getBytes());

      // Get credential from Funcion compute service 
      Credentials creds = context.getExecutionCredentials();

      String AccessID= creds.getAccessKeyId();
      String AccessKey= creds.getAccessKeySecret();
      String SecurityToken =creds.getSecurityToken();

           //outputStream.write(new String("Secret AccessID:"+AccessID +" \n").getBytes());
           //outputStream.write(new String("Secret AccessKey:"+AccessKey +" \n").getBytes());

       //DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret);
       DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", AccessID, AccessKey,SecurityToken);

       IAcsClient client = new DefaultAcsClient(profile);

      // Get secret data from KMS
        GetSecretValueRequest request = new GetSecretValueRequest();
        request.setSecretName(kmssecret);
      
   
    CloudAccount account = new CloudAccount(AccessID,AccessKey,ServiceSettings.getMNSAccountEndpoint(),SecurityToken);
    
    //DefaultMNSClient MNSclient = new DefaultMNSClient(creds.getAccessKeyId(), creds.getAccessKeySecret(),MNSEndpoint) ;

    CloudTopic topic = MNSclient.getTopicRef("myTopic");
      
    try
       {
           GetSecretValueResponse response = client.getAcsResponse(request);
            
           **if (response== null)
           {
              
               throw new Exception("Cant connect to KMS"); 
           }**
           JSONObject obj= new JSONObject(response);
           
           String SecretData = obj.getString("secretData");
           
           JSONObject SecretData1= new JSONObject(SecretData);
           
           String user = SecretData1.getString("username");
           String password = SecretData1.getString("password");
           String host = SecretData1.getString("host");
           String port1 = SecretData1.getString("port");
           int port=Integer.parseInt(port1);  
           String remotePath = SecretData1.getString("remotepath");

            // Print values got from KMS Secret
           outputStream.write(new String("Secret UserName:"+user +" \n").getBytes());
           outputStream.write(new String("Secret Password:"+password +" \n").getBytes());
           outputStream.write(new String("Secret Host:"+host +" \n").getBytes());
           outputStream.write(new String("Secret Port:"+port1 +" \n").getBytes());
           outputStream.write(new String("Secret remotePath:"+remotePath +" \n\n").getBytes());
      
           //TopicMessage msg1 = new TopicMessage(); // You can specify whether to perform Base64 encoding on topic messages.
           TopicMessage  msg = new RawTopicMessage();  
           //TopicMessage  msg1 = new RawTopicMessage(); 

           outputStream.write(new String("hello world to AliCloud\n").getBytes());
          // Create an OSSClient instance.
          outputStream.write(new String("Start to create OSS client\n").getBytes());
         // OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
         OSS ossClient = new OSSClientBuilder().build(endpoint, creds.getAccessKeyId(), creds.getAccessKeySecret() ,creds.getSecurityToken());

          outputStream.write(new String("OSS client created.\n").getBytes());

          JSch jsch = new JSch();
          outputStream.write(new String("Jsch instanciated\n").getBytes());
          
          Session session = jsch.getSession(user, host, port);
          session.setPassword(password);
          // rational
          session.setConfig("StrictHostKeyChecking", "no");

          outputStream.write(new String("Jsch session created, Establishing Connection...\n").getBytes());
          session.connect();
          outputStream.write(new String("...Connection established\n").getBytes());
          outputStream.write(new String("establish sftp channel...\n").getBytes());
          ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
          sftpChannel.connect();
          outputStream.write(new String("...sftp channel established\n").getBytes());

          sftpChannel.cd(remotePath);
            outputStream.write(new String("...changed directory\n").getBytes());

            Vector lsVector = sftpChannel.ls("*");
          outputStream.write(new String("ls vector created\n").getBytes());

          Enumeration en = lsVector.elements();
          outputStream.write(new String("ls elements are:\n").getBytes());
          String filename;
          ChannelSftp.LsEntry LsEntry;

          if(lsVector.isEmpty()==true) 
          {
              outputStream.write(new String("Publish Message \n").getBytes());

              //msg.setMessageBody("hello world!") ;
              msg.setMessageBody(("hello bytes with tag! ").getBytes());

              msg = topic.publishMessage(msg);  
           throw new Exception("No File Found"); 
          }
          else
          {
          while(en.hasMoreElements()) 
          {
         LsEntry = (ChannelSftp.LsEntry)en.nextElement();
          filename = LsEntry.getFilename();
           // else {
           outputStream.write(new String(filename+" \n").getBytes());
           
           InputStream fileIS = sftpChannel.get(filename);
           // filename with extension ?
           ossClient.putObject(bucketname, filename, fileIS);
           
           // remove remote file from FTP server
           sftpChannel.rm(filename);
          // }
         }
          }      
          // Shut down the OSSClient instance.
          ossClient.shutdown();

          sftpChannel.disconnect();
          outputStream.write(new String("sftp channel disconnected\n").getBytes());
          session.disconnect();
            outputStream.write(new String("disconnected from session\n").getBytes());
       }
       catch(Exception e)
       {
           outputStream.write(new String("Error Message:"+e.getMessage() +" \n\n").getBytes());
           
       }
       }
   
    }

基本上,我希望捕获运行时出现的错误,并在此基础上执行一些操作

例如:

if exception=Forbidden.NoPermission
then 
Publish a message in topic with the error message occurs.

这里详细介绍了阿里云KMS的错误描述

https://error-center.alibabacloud.com/status/product/Kms?spm=a2c69.11428812.home.32.1f39bb9amMIo4u

有人能帮我捕获错误并在MNS中发布消息吗

谢谢, 安多


共 (1) 个答案

  1. # 1 楼答案

    我假设您将async调用该函数,而不是sync调用它。如果是这样,有一个更简单的解决方案,您不需要编写代码来通知MNS

    阿里云函数计算支持Destination feature

    过程如下:

    1. 为函数配置异步调用配置-当函数异常返回时,通知MNS主题
    2. 在函数中,调用KMS。如果成功了,你就做你的业务逻辑;否则只抛出异常

    就这样