Skip to content

Add an error code to the unkown option error#8

Merged
rauchg merged 4 commits intomasterfrom
fix/errors
Dec 3, 2018
Merged

Add an error code to the unkown option error#8
rauchg merged 4 commits intomasterfrom
fix/errors

Conversation

@matheuss
Copy link
Member

Before:

let args
try {
  args = arg(...)
} catch (err) {
  if (err.message.startsWith('Unknown or unexpected option:')) {
    // print a nice error
  }
}

After:

let args
try {
  args = arg(...)
} catch (err) {
  if (err.code === 'UNKNOWN_OPTION') {
    // print a nice error
  }
}

@matheuss matheuss requested a review from Qix- April 12, 2018 15:28
@Qix-
Copy link
Contributor

Qix- commented Apr 20, 2018

I'm 👎 on this since IMO .code is reserved for errno codes.

However, including the parser state in the error message as properties wouldn't be the worst.

@bpierre
Copy link

bpierre commented May 30, 2018

Another approach would be to export custom error types.

In arg:

// Utility function to create custom errors
const createError = name => class extends Error {
  constructor(message) {
    super(message);
    this.name = name;
  }
};

// Custom error types
const UnknownOrUnexpectedOptionError = createError('UnknownOrUnexpectedOptionError');
const MissingOptionArgumentError = createError('MissingOptionArgumentError');
// …

// And thrown this way
throw new UnknownOrUnexpectedOptionError(`Unknown or unexpected option: ${originalArgName}`);

It would then make it easy to know what error is being thrown:

const arg = require('arg');
const { UnknownOrUnexpectedOptionError } = arg;

try {
  const args = arg({ /* … */ });
} catch (err) {
  if (err instanceof UnknownOrUnexpectedOptionError) {
    // handle the error gracefully
  }
}

@rauchg
Copy link
Member

rauchg commented Dec 2, 2018

.code is not reserved. Node.js just uses it.

@matheuss can you:

  • rename the code to ARG_UNKNOWN_OPTION (prefixing it with the project name seems sensible)
  • add a note about this in the README

rauchg
rauchg previously requested changes Dec 2, 2018
Copy link
Member

@rauchg rauchg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rauchg rauchg requested review from rauchg and removed request for Qix- December 2, 2018 00:40
@Qix- Qix- self-requested a review December 3, 2018 17:43
@rauchg rauchg merged commit efe23dc into master Dec 3, 2018
@rauchg rauchg deleted the fix/errors branch December 3, 2018 23:14
nevilm-lt pushed a commit to nevilm-lt/arg that referenced this pull request Apr 22, 2022
* Add an error code to the `unkown option` error

So it's easier to catch it

* Change error code

* Document

* Fix markdown
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants