如何从Google脚本发送错误状态代码(如错误请求(400))? [英] How to send an error status code like Bad Request (400) from a google script?

查看:61
本文介绍了如何从Google脚本发送错误状态代码(如错误请求(400))?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Google App中的 doPost 函数,它返回 Hello World 消息.

  function doPost(e){返回ContentService.createTextOutput('Hello World');} 

现在,假设我只想接受将有效的JSON发布到此Google App端点,并且我想发送状态为错误请求"的响应.我怎样才能做到这一点.这是伪代码:

  function doPost(e){尝试{const data = JSON.parse(e.postData.contents);返回ContentService.createTextOutput('Hello World');} catch(err){//发送错误的请求}} 

解决方案

问题和解决方法:

不幸的是,在当前阶段, ContentService 无法修改状态代码.当我看到Class ContentService的正式文档时,找不到这种方法.参考看来,这是当前的规范.

因此,在您的情况下,作为当前的解决方法,如何将值作为JSON数据返回?这样,您可以使用JSON数据的密钥检查值.例如,下面的示例脚本怎么样?

  • 返回没有错误的正确值时,

      return ContentService.createTextOutput(JSON.stringify({value:'value'}));; 

  • 返回错误值时,

      return ContentService.createTextOutput(JSON.stringify({error:'Error message'}))); 

  • 当您需要 .setMimeType(ContentService.MimeType.JSON)时,请添加此代码.

注意:

  • 当我在Google问题跟踪器中搜索到此内容时,找不到它.那么,将其报告为将来的请求又如何呢?参考

参考:

This is a doPost function inside a Google App that returns a Hello World message.

function doPost(e){

  return ContentService.createTextOutput('Hello World');
} 

Now suppose I want to only accept valid JSON to be posted to this Google App endpoint and I want to send a respones with Bad Request status. How can I do that. Here's the pseudo code:

function doPost(e){
  try{
     const data = JSON.parse(e.postData.contents);
     return ContentService.createTextOutput('Hello World');
  }catch(err){
      // Send Bad Request
  }      

} 

解决方案

Issue and workaround:

Unfortunately, in the current stage, ContentService cannot modify the status code. When I saw the official document of Class ContentService, such method cannot be found. Ref It seems that this is the current specification.

So in your situation, as the current workaround, how about returning the value as JSON data? By this, you can check the value using the key of JSON data. For example, how about the following sample script?

  • When the correct value without the error is returned,

      return ContentService.createTextOutput(JSON.stringify({value: 'value'}));
    

  • When the value with the error is returned,

      return ContentService.createTextOutput(JSON.stringify({error: 'Error message'}));
    

  • When you need .setMimeType(ContentService.MimeType.JSON), please add this.

Note:

  • When I searched about this at the Google issue tracker, I couldn't find it. So how about reporting this as the future request? Ref

Reference:

这篇关于如何从Google脚本发送错误状态代码(如错误请求(400))?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆