如何摆脱nodejs中try-catch块中的语法错误

我在 controller.js 文件中使用以下代码。在本地机器上运行时,代码正在运行 finr,但在 aws ec2 机器上运行时,我收到错误。你能帮我解决这个问题吗?


query(request_body,(results,error) =>{

      if (error){

        return res.status(404).json(error);

      }

      if (results){

        try{

              if (results.Items.length == 0 ) {

                error_msg = {"message":"No record found for  given search criteria"};

                return res.status(404).json(error_msg)

              } else {

                return res.status(200).json(results)

              }

           } 

        catch { 

          return res.status(200).json(results)

        }

      }       

    }

  )

错误:


home/ubuntu/node-temp/api/src/user.controller.js:30

        catch {

              ^


SyntaxError: Unexpected token {

    at createScript (vm.js:80:10)

    at Object.runInThisContext (vm.js:139:10)

    at Module._compile (module.js:616:28)

    at Object.Module._extensions..js (module.js:663:10)

    at Module.load (module.js:565:32)

    at tryModuleLoad (module.js:505:12)

    at Function.Module._load (module.js:497:3)

    at Module.require (module.js:596:17)

    at require (internal/module.js:11:18)

    at Object.<anonymous> (/home/ubuntu/node-temp/api/src/user.router.js:2:78)


蛊毒传说
浏览 124回答 2
2回答

呼如林

try {&nbsp; &nbsp; // code} catch {}这称为可选的 catch 绑定。将您的节点版本更新到至少10.3.0或将您的代码更改为类似以下内容:try {&nbsp; &nbsp; &nbsp;// code} catch (_unused) {}

慕工程0101907

尝试 catch 语法如下所示try {&nbsp; &nbsp;...stuff&nbsp;} catch (error) {&nbsp; &nbsp;console.log(error)}https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch所以它看起来像这样query(request_body,(results,error) =>{&nbsp; &nbsp; &nbsp; if (error){&nbsp; &nbsp; &nbsp; &nbsp; return res.status(404).json(error);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; if (results){&nbsp; &nbsp; &nbsp; &nbsp; try{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (results.Items.length == 0 ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; error_msg = {"message":"No record found for&nbsp; given search criteria"};&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return res.status(404).json(error_msg)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return res.status(200).json(results)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; catch (error) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return res.status(200).json(results)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; }&nbsp; )
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript