简体   繁体   English

如何使用try catch语句抛出错误?

[英]How to throw an error using try catch statement?

//Utility
  const readUserUtility = (id_a)=>{
    const currentstore = store.getState();
    const returnedArray = currentstore.users.filter((user_object)=>{
        return user_object.id === id_a;
    })

    try{if(returnedArray.length === 0){throw "Array empty";}}catch(error){
    console.log(error);


    }

    console.log(returnedArray);
  }

I have this function readUserUtility as part of a redux application.我有这个函数 readUserUtility 作为 redux 应用程序的一部分。 When i call readuserUtility with an integer im getting the error: Line 144: Expected an object to be thrown no-throw-literal当我使用整数调用 readuserUtility 时,我收到错误:第 144 行:预期要抛出一个对象 no-throw-literal

The message "Array empty" still shows up in the console, but why am i getting this error?消息“Array empty”仍然显示在控制台中,但为什么我会收到这个错误?

You have to create a new Error object and pass that.您必须创建一个新的 Error 对象并传递它。 Below works for me:以下对我有用:

throw new Error("item not found");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM