Error expected an object to be thrown no throw literal

A pluggable and configurable linter tool for identifying and reporting on patterns in JavaScript. Maintain your code quality with ease.

Disallow throwing literals as exceptions

It is considered good practice to only throw the Error object itself or an object using the Error object as base objects for user-defined exceptions.
The fundamental benefit of Error objects is that they automatically keep track of where they were built and originated.

This rule restricts what can be thrown as an exception. When it was first created, it only prevented literals from being thrown (hence the name), but it has now been expanded to only allow expressions which have a possibility of being an Error object.

Rule Details

This rule is aimed at maintaining consistency when throwing exception by disallowing to throw literals and other expressions which cannot possibly be an Error object.

Examples of incorrect code for this rule:

/*eslint no-throw-literal: "error"*/
/*eslint-env es6*/

throw "error";

throw 0;

throw undefined;

throw null;

var err = new Error();
throw "an " + err;
// err is recast to a string literal

var err = new Error();
throw `${err}`

Examples of correct code for this rule:

/*eslint no-throw-literal: "error"*/

throw new Error();

throw new Error("error");

var e = new Error("error");
throw e;

try {
    throw new Error("error");
} catch (e) {
    throw e;
}

Known Limitations

Due to the limits of static analysis, this rule cannot guarantee that you will only throw Error objects.

Examples of correct code for this rule, but which do not throw an Error object:

/*eslint no-throw-literal: "error"*/

var err = "error";
throw err;

function foo(bar) {
    console.log(bar);
}
throw foo("error");

throw new String("error");

var foo = {
    bar: "error"
};
throw foo.bar;

Version

This rule was introduced in ESLint v0.15.0.

Resources

  • Rule source
  • Tests source
title layout

Rule no-throw-literal

doc

Restrict what can be thrown as an exception (no-throw-literal)

It is considered good practice to only throw the Error object itself or an object using the Error object as base objects for user-defined exceptions.
The fundamental benefit of Error objects is that they automatically keep track of where they were built and originated.

This rule restricts what can be thrown as an exception. When it was first created, it only prevented literals from being thrown (hence the name), but it has now been expanded to only allow expressions which have a possibility of being an Error object.

Rule Details

This rule is aimed at maintaining consistency when throwing exception by disallowing to throw literals and other expressions which cannot possibly be an Error object.

The following patterns are considered problems:

/*eslint no-throw-literal: 2*/
/*eslint-env es6*/

throw "error";         /*error Expected an object to be thrown.*/

throw 0;               /*error Expected an object to be thrown.*/

throw undefined;       /*error Do not throw undefined.*/

throw null;            /*error Expected an object to be thrown.*/

var err = new Error();
throw "an " + err;     /*error Expected an object to be thrown.*/
// err is recast to a string literal

var err = new Error();
throw `${err}`         /*error Expected an object to be thrown.*/

The following patterns are not considered problems:

/*eslint no-throw-literal: 2*/

throw new Error();

throw new Error("error");

var e = new Error("error");
throw e;

try {
    throw new Error("error");
} catch (e) {
    throw e;
}

Known Limitations

Due to the limits of static analysis, this rule cannot guarantee that you will only throw Error objects. For instance, the following cases do not throw an Error object, but they will not be considered problems:

/*eslint no-throw-literal: 2*/

var err = "error";
throw err;

function foo(bar) {
    console.log(bar);
}
throw foo("error");

throw new String("error");

var foo = {
    bar: "error"
};
throw foo.bar;

Version

This rule was introduced in ESLint 0.15.0.

Resources

  • Rule source
  • Documentation source

Below throw code giving lint error Expected an object to be thrown no-throw-literal

throw { code : 403, message : myMessage };

if i try throw new Error, i am not getting eslint but it gives [Object Object] in the response.

throw new Error({ code : 403, message : myMessage });

Could someone tell me how to fix Expected an object to be thrown error ? without removing eslint config/rules

asked Oct 31, 2018 at 10:12

Munna Babu's user avatar

2

 throw Object.assign(
   new Error(myMessage),
   { code: 402 }
);

Throw a regular error and extend it with custom fields.


You could also write a reusable error class for that:

  class CodeError extends Error {
   constructor(message, code) {
    super(message);
    this.code = code;
   }
 }

 throw new CodeError(myMessage, 404);

That way, you can distinguish the errors easily on catching:

  } catch(error) {
    if(error instanceof CodeError) {
      console.log(error.code);
    } else {
      //...
    }
 }

Community's user avatar

answered Oct 31, 2018 at 10:17

Jonas Wilms's user avatar

Jonas WilmsJonas Wilms

128k20 gold badges142 silver badges149 bronze badges

Another simple workaround is store on variable and throw.

const errorMessage =  { code : 403, message : myMessage };
throw errorMessage;

answered Nov 21, 2018 at 9:47

Munna Babu's user avatar

Munna BabuMunna Babu

5,3266 gold badges28 silver badges44 bronze badges

2

Запретить бросать литералы в качестве исключений

Считается хорошей практикой throw только сам объект Error или объект, использующий объект Error в качестве базовых объектов для определяемых пользователем исключений. Основное преимущество объектов Error заключается в том, что они автоматически отслеживают, где они были созданы и возникли.

Это правило ограничивает то, что может быть выбрано как исключение. Когда он был впервые создан, он только предотвращал выброс литералов (отсюда и название), но теперь он был расширен, чтобы разрешить только выражения, которые могут быть объектом Error .

Rule Details

Это правило направлено на поддержание согласованности при генерировании исключения, запрещая генерировать литералы и другие выражения, которые не могут быть объектом Error .

Примеры неправильного кода для этого правила:

throw "error";throw 0;throw undefined;throw null;var err = new Error();throw "an " + err;

Примеры правильного кода для этого правила:

throw new Error();throw new Error("error");var e = new Error("error");throw e;try {    throw new Error("error");} catch (e) {    throw e;}

Known Limitations

Из-за ограничений статического анализа это правило не может гарантировать, что вы будете генерировать только объекты Error .

Примеры правильного кода для этого правила, но не генерирующего объект Error :

var err = "error";throw err;function foo(bar) {    console.log(bar);}throw foo("error");throw new String("error");var foo = {    bar: "error"};throw foo.bar;

Version

Это правило было введено в ESLint v0.15.0.

Resources

  • Rule source
  • Tests source


ESLint

8.30

  • no-ternary

    Запретить троичные операторы Троичный оператор используется для условного присвоения переменной значения.

  • no-this-before-super

    Запретить this/super перед вызовом конструкторов Свойство «extends»: «eslint:recommended» файл конфигурации включает это правило В конструкторе

  • no-trailing-spaces

    Запретить пробельные символы в конце строк Некоторые проблемы,о которых сообщает это правило,автоматически устраняются опцией командной строки Иногда в

  • no-undef

    Запретить использование необъявленных переменных, если они не указаны в /*глобальных комментариях. Свойство «extends»: «eslint:recommended» разрешает файл конфигурации.

Q1: В экспорте отчета используются Fetch используются, и теперь вам нужно обрабатывать ситуацию: интерфейс будет иметь состояние возврата 404.

  handleExport = () =>{
    if( this.state.type === ''){
        Message.warning ('Пожалуйста, выберите область сначала);
    }else{
        getToken().then(token=>{
            const url = `${Url()}shopping_mall/reports/rank/export?from_date=${getStartDate(this.state.stDate)}&to_date=${getEndDate(this.state.endDate)}&order_by=${this.state.orderBy}&${this.state.type}`;
            const fetchOption = {
              method: 'GET',
              headers: {
                'X-Requested-With': '1000',
                Authorization: `Bearer ${token}`,
              },
            };
                         // начать загрузку необходимых данных
            fetch(url, fetchOption)
              .then(response => response.blob())
              .then(blob=>{
                const aUrl = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = aUrl;
                document.body.appendChild(a);
                                 A.Download = "Сведения о данных. CSV";
                a.click();
                setTimeout(()=>{
                  document.body.removeChild(a);
                  window.URL.revokeObjectURL(aUrl);
                },2000);
              })
          })
    }
  }

После модификации

  handleExport = () =>{
    if( this.state.type === ''){
                 Message.warning ('Пожалуйста, выберите область сначала);
    }else{
        getToken().then(token=>{
            const url = `${Url()}shopping_mall/reports/rank/export?from_date=${getStartDate(this.state.stDate)}&to_date=${getEndDate(this.state.endDate)}&order_by=${this.state.orderBy}&${this.state.type}`;
            const fetchOption = {
              method: 'GET',
              headers: {
                'X-Requested-With': '1000',
                Authorization: `Bearer ${token}`,
              },
            };
            return new Promise((resolve, reject) => {
                             // начать загрузку необходимых данных
              fetch(url, fetchOption)
                .then(response => {
                  // console.log('response = ', response);
                  if(response.ok){
                    return response.blob();
                  }else{
                                         Message.warning («Нет данных не экспортирован»);
                    throw `${response.statusText}`;
                    // throw new Error("error");
                    // message.error('')
                  }
                })
              .then(blob=>{
                const aUrl = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = aUrl;
                document.body.appendChild(a);
                                 A.Download = "Сведения о данных. CSV";
                a.click();
                setTimeout(()=>{
                  document.body.removeChild(a);
                  window.URL.revokeObjectURL(aUrl);
                },2000);
              })
              .catch(err => {
                reject(err);
              });
            });

          })
    }
  }

Существует ошибка синтаксиса ESLING ESLING:

expected an object to be thrown. (no-throw-literal)

Потому что грамматика написана в этом:throw new Error(${response.statusText});(Спецификация синтаксиса:https://cn.eslint.org/docs/rules/no-throw-literalЭто, затем изменилось, но когда страница экспортируется, после того, как состояние 404, он будет перейти на страницу ошибки, а пользовательский опыт не является дружественным, и я не знаю, как это решить. Отметьте первым

Поэтому я до сих пор пишу форму ошибки синтаксиса:throw${response.statusText};Это не будет перейти на интерфейс ошибок.

Ссылочный источник:http://react-china.org/t/fetch-then/7054


Closed

Bug 1256768


Opened 7 years ago
Closed 6 years ago

Categories

(DevTools :: Console, defect, P3)

Tracking

(firefox55 fixed)

Tracking Status
firefox55 fixed

People

(Reporter: linclark, Assigned: mkohler, Mentored)

References

Details

(Whiteboard: [btpp-backlog])

Attachments

(1 file, 2 obsolete files)

Whiteboard: [btpp-backlog]

Assignee: nobody → mkohler

Status: NEW → ASSIGNED

Comment on attachment 8744641 [details] [diff] [review]
0001-Fix-ESLint-Errors-in-console-output.js.patch

Review of attachment 8744641 [details] [diff] [review]:
-----------------------------------------------------------------

Thanks for the patch! There are some failures in there that aren't already marked as intermittent, so I'd like to see a cleaner try run before committing. For example: 151 INFO TEST-UNEXPECTED-FAIL | devtools/client/webconsole/test/browser_webconsole_bug_922212_console_dirxml.js | The ElementNode widget isn't linked to the inspector -

::: devtools/client/webconsole/console-output.js
@@ +2406,5 @@
>      let { preview } = this.objectActor;
>      let { ownProperties, safeGetterValues } = preview;
>      let shown = 0;
>      let getValue = desc => {
> +      let value = "";

The else should be catching anything that hasn't already returned. Can we just remove the `else` wrapper around return `desc.value` so that it's clear that that's the default return?

@@ -3080,5 @@
>        case Ci.nsIDOMNode.DOCUMENT_NODE:
>          this._renderDocumentNode();
>          break;
>        case Ci.nsIDOMNode.ATTRIBUTE_NODE: {
> -        let {preview} = this.objectActor;

So this removes the assignment of preview, but it looks like preview is used below. WHat rule was this hitting?

@@ +3247,5 @@
>      let isAttached = yield this.toolbox.walker.isInDOMTree(this._nodeFront);
>      if (isAttached) {
>        yield this.toolbox.highlighterUtils.highlightNodeFront(this._nodeFront);
>      } else {
> +      throw new Error("node is not attached");

Hm, this actually changes what the code does. While I don't think throwing null is a good thing to do here, changing it might break things. I'm not sure if anything depends on this being how it is. Out of curiosity, which rule is this hitting?
(In reply to Lin Clark [:linclark] from comment #2)
> ::: devtools/client/webconsole/console-output.js
> @@ +2406,5 @@
> >      let { preview } = this.objectActor;
> >      let { ownProperties, safeGetterValues } = preview;
> >      let shown = 0;
> >      let getValue = desc => {
> > +      let value = "";
> 
> The else should be catching anything that hasn't already returned. Can we
> just remove the `else` wrapper around return `desc.value` so that it's clear
> that that's the default return?

The thing is that we're hitting this rule:

2416:15  error  Unexpected 'else' after 'return'                        no-else-return

We probably want to set desc.value as default and then overwrite it if necessary. Updated my patch to do that.


> @@ -3080,5 @@
> >        case Ci.nsIDOMNode.DOCUMENT_NODE:
> >          this._renderDocumentNode();
> >          break;
> >        case Ci.nsIDOMNode.ATTRIBUTE_NODE: {
> > -        let {preview} = this.objectActor;
> 
> So this removes the assignment of preview, but it looks like preview is used
> below. WHat rule was this hitting?

This was hitting

3026:14  error  'preview' is already declared in the upper scope  no-shadow

but my fix is bad since it's not given that it's the same. We might need to change the rules, I have no idea where the "upper scope" might come from to be honest.


> @@ +3247,5 @@
> >      let isAttached = yield this.toolbox.walker.isInDOMTree(this._nodeFront);
> >      if (isAttached) {
> >        yield this.toolbox.highlighterUtils.highlightNodeFront(this._nodeFront);
> >      } else {
> > +      throw new Error("node is not attached");
> 
> Hm, this actually changes what the code does. While I don't think throwing
> null is a good thing to do here, changing it might break things. I'm not
> sure if anything depends on this being how it is. Out of curiosity, which
> rule is this hitting?


3252:7   error  Expected an object to be thrown                   no-throw-literal

What would you suggest here?



In summary:

/Users/mkohler/development/gecko-dev/devtools/client/webconsole/console-output.js
  3026:14  error  'preview' is already declared in the upper scope  no-shadow
  3252:7   error  Expected an object to be thrown                   no-throw-literal

Patch is updated to latest code changes.


Please also note that I haven't run the tests so far since it's WIP.
Sorry for the delay.

> 3026:14  error  'preview' is already declared in the upper scope  no-shadow

upper scope would be the scope outside of the switch/case. let uses what's called block scoping.

> 3252:7   error  Expected an object to be thrown                   no-throw-literal
> What would you suggest here?

If we run the tests and it doesn't break anything, then throwing an error (as you have done) is probably the best thing here. The only change is to capitalize/punctuate the error message.
Comment on attachment 8856211 [details]
Bug 1256768 - Fix ESLint errors/warnings in devtools/client/webconsole/console-output.js

Hello Michael, thanks for working on this !
Lin is not in the team anymore so you can ask either bgrins or I (nchevobbe) for review on the console.
I will review your patch tomorrow morning :)
Comment on attachment 8856211 [details]
Bug 1256768 - Fix ESLint errors/warnings in devtools/client/webconsole/console-output.js

https://reviewboard.mozilla.org/r/128156/#review130786

Overall this looks good, I only have a few nits.
I pushed to TRY with a broader set of tests to make sure there's nothing we missed : https://treeherder.mozilla.org/#/jobs?repo=try&revision=e0c36526f65e697b4659f6a8898e221a40da73b4&selectedJob=90014786
If this is green, feel free to land your patch after fixing the 2 issues in the review.

Thanks

::: devtools/client/webconsole/console-output.js:2294
(Diff revision 1)
> -  _renderObjectProperty: function (key, value, container, needsComma, valueIsText = false)
> -  {
> +  _renderObjectProperty: function (key, value, container, needsComma,
> +                                   valueIsText = false) {

I think we could make this more readable like this :
```
_renderObjectProperty: function (
  key, 
  value, 
  container, 
  needsComma,
  valueIsText = false
) {

```

What do you think ?

::: devtools/client/webconsole/console-output.js:2921
(Diff revision 1)
>    },
>  
> -  render: function ()
> -  {
> +  render: function () {
> +    const {preview} = this.objectActor;
> +
>      switch (this.objectActor.preview.nodeType) {

here we could can now use `preview.nodeType` insteqd of `this.objectActor.preview.nodeType`

::: devtools/client/webconsole/console-output.js:3104
(Diff revision 1)
> -    this._nodeFront = yield this.toolbox.walker.getNodeActorFromObjectActor(this.objectActor.actor);
> +    const walker = this.toolbox.walker;
> +    this._nodeFront = yield walker.getNodeActorFromObjectActor(this.objectActor.actor);

I don't think we need to create a single use new variable here.
What do you think of :
```
this._nodeFront = yield this.toolbox.walker.getNodeActorFromObjectActor(
  this.objectActor.actor);
```

Product: Firefox → DevTools

You need to log in
before you can comment on or make changes to this bug.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error during initialization fatal error
  • Error during initialization couldn t load default
  • Error 777 3g modem
  • Error exe 001 на телевизоре самсунг ошибка
  • Error 773 что это

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии