阿里云java捕获和引发事件的错误处理

f0brbegy  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(359)

我对java和学习曲线都是新手。我在阿里云集成了一个java函数compute。
我需要连接到密钥管理服务(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中发布消息吗?
谢谢,安多

vd8tlhqk

vd8tlhqk1#

我假设您将异步调用函数,而不是同步调用它。如果是这样,有一个更简单的解决方案,您不需要编写代码来通知mns。
阿里云功能计算支持目的地功能
过程如下:
为函数配置async invoke config—当函数异常返回时,通知mns主题。
在函数中,调用kms。如果成功了,你就按照你的商业逻辑去做;否则就抛出异常。
就这样!

相关问题