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

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

我对java和学习曲线都是新手。我在阿里云集成了一个java函数compute。
我需要连接到密钥管理服务(kms)以获取机密。如果kms不可用或无法通过函数连接,那么我需要在mns的主题中创建一个事件消息。我想知道如何处理这个错误?
下面是代码段。

  1. public class SFTP14 implements StreamRequestHandler, FunctionInitializer {
  2. public void initialize(Context context) throws IOException {
  3. }
  4. public void handleRequest( InputStream inputStream
  5. , OutputStream outputStream
  6. , Context context) throws IOException
  7. {
  8. // Get values from Environment varaible of function
  9. String bucketname = System.getenv("BUCKET_NAME");
  10. String endpoint = System.getenv("ENDPOINT");
  11. String kmssecret = System.getenv("KMSSECRET");
  12. String MNSEndpoint="http://mns.cn-shanghai.aliyuncs.com/";
  13. outputStream.write(new String("Bucket Name:"+bucketname +" \n").getBytes());
  14. outputStream.write(new String("End Point Name:"+endpoint +" \n").getBytes());
  15. // Get credential from Funcion compute service
  16. Credentials creds = context.getExecutionCredentials();
  17. String AccessID= creds.getAccessKeyId();
  18. String AccessKey= creds.getAccessKeySecret();
  19. String SecurityToken =creds.getSecurityToken();
  20. //outputStream.write(new String("Secret AccessID:"+AccessID +" \n").getBytes());
  21. //outputStream.write(new String("Secret AccessKey:"+AccessKey +" \n").getBytes());
  22. //DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret);
  23. DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", AccessID, AccessKey,SecurityToken);
  24. IAcsClient client = new DefaultAcsClient(profile);
  25. // Get secret data from KMS
  26. GetSecretValueRequest request = new GetSecretValueRequest();
  27. request.setSecretName(kmssecret);
  28. CloudAccount account = new CloudAccount(AccessID,AccessKey,ServiceSettings.getMNSAccountEndpoint(),SecurityToken);
  29. //DefaultMNSClient MNSclient = new DefaultMNSClient(creds.getAccessKeyId(), creds.getAccessKeySecret(),MNSEndpoint) ;
  30. CloudTopic topic = MNSclient.getTopicRef("myTopic");
  31. try
  32. {
  33. GetSecretValueResponse response = client.getAcsResponse(request);
  34. **if (response== null)
  35. {
  36. throw new Exception("Cant connect to KMS");
  37. }**
  38. JSONObject obj= new JSONObject(response);
  39. String SecretData = obj.getString("secretData");
  40. JSONObject SecretData1= new JSONObject(SecretData);
  41. String user = SecretData1.getString("username");
  42. String password = SecretData1.getString("password");
  43. String host = SecretData1.getString("host");
  44. String port1 = SecretData1.getString("port");
  45. int port=Integer.parseInt(port1);
  46. String remotePath = SecretData1.getString("remotepath");
  47. // Print values got from KMS Secret
  48. outputStream.write(new String("Secret UserName:"+user +" \n").getBytes());
  49. outputStream.write(new String("Secret Password:"+password +" \n").getBytes());
  50. outputStream.write(new String("Secret Host:"+host +" \n").getBytes());
  51. outputStream.write(new String("Secret Port:"+port1 +" \n").getBytes());
  52. outputStream.write(new String("Secret remotePath:"+remotePath +" \n\n").getBytes());
  53. //TopicMessage msg1 = new TopicMessage(); // You can specify whether to perform Base64 encoding on topic messages.
  54. TopicMessage msg = new RawTopicMessage();
  55. //TopicMessage msg1 = new RawTopicMessage();
  56. outputStream.write(new String("hello world to AliCloud\n").getBytes());
  57. // Create an OSSClient instance.
  58. outputStream.write(new String("Start to create OSS client\n").getBytes());
  59. // OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
  60. OSS ossClient = new OSSClientBuilder().build(endpoint, creds.getAccessKeyId(), creds.getAccessKeySecret() ,creds.getSecurityToken());
  61. outputStream.write(new String("OSS client created.\n").getBytes());
  62. JSch jsch = new JSch();
  63. outputStream.write(new String("Jsch instanciated\n").getBytes());
  64. Session session = jsch.getSession(user, host, port);
  65. session.setPassword(password);
  66. // rational
  67. session.setConfig("StrictHostKeyChecking", "no");
  68. outputStream.write(new String("Jsch session created, Establishing Connection...\n").getBytes());
  69. session.connect();
  70. outputStream.write(new String("...Connection established\n").getBytes());
  71. outputStream.write(new String("establish sftp channel...\n").getBytes());
  72. ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  73. sftpChannel.connect();
  74. outputStream.write(new String("...sftp channel established\n").getBytes());
  75. sftpChannel.cd(remotePath);
  76. outputStream.write(new String("...changed directory\n").getBytes());
  77. Vector lsVector = sftpChannel.ls("*");
  78. outputStream.write(new String("ls vector created\n").getBytes());
  79. Enumeration en = lsVector.elements();
  80. outputStream.write(new String("ls elements are:\n").getBytes());
  81. String filename;
  82. ChannelSftp.LsEntry LsEntry;
  83. if(lsVector.isEmpty()==true)
  84. {
  85. outputStream.write(new String("Publish Message \n").getBytes());
  86. //msg.setMessageBody("hello world!") ;
  87. msg.setMessageBody(("hello bytes with tag! ").getBytes());
  88. msg = topic.publishMessage(msg);
  89. throw new Exception("No File Found");
  90. }
  91. else
  92. {
  93. while(en.hasMoreElements())
  94. {
  95. LsEntry = (ChannelSftp.LsEntry)en.nextElement();
  96. filename = LsEntry.getFilename();
  97. // else {
  98. outputStream.write(new String(filename+" \n").getBytes());
  99. InputStream fileIS = sftpChannel.get(filename);
  100. // filename with extension ?
  101. ossClient.putObject(bucketname, filename, fileIS);
  102. // remove remote file from FTP server
  103. sftpChannel.rm(filename);
  104. // }
  105. }
  106. }
  107. // Shut down the OSSClient instance.
  108. ossClient.shutdown();
  109. sftpChannel.disconnect();
  110. outputStream.write(new String("sftp channel disconnected\n").getBytes());
  111. session.disconnect();
  112. outputStream.write(new String("disconnected from session\n").getBytes());
  113. }
  114. catch(Exception e)
  115. {
  116. outputStream.write(new String("Error Message:"+e.getMessage() +" \n\n").getBytes());
  117. }
  118. }
  119. }

基本上,我想捕获运行时出现的错误,并在此基础上执行一些操作。
例如:

  1. if exception=Forbidden.NoPermission
  2. then
  3. 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。如果成功了,你就按照你的商业逻辑去做;否则就抛出异常。
就这样!

相关问题