문제

I'm writing a JavaScript function that makes an HTTP request and returns a promise for the result (but this question applies equally for a callback-based implementation).

If I know immediately that the arguments supplied for the function are invalid, should the function throw synchronously, or should it return a rejected promise (or, if you prefer, invoke callback with an Error instance)?

How important is it that an async function should always behave in an async manner, particularly for error conditions? Is it OK to throw if you know that the program is not in a suitable state for the async operation to proceed?

e.g:

function getUserById(userId, cb) {
  if (userId !== parseInt(userId)) {
    throw new Error('userId is not valid')
  }

  // make async call
}

// OR...

function getUserById(userId, cb) {
  if (userId !== parseInt(userId)) {
    return cb(new Error('userId is not valid'))
  }

  // make async call
}
도움이 되었습니까?

해결책

Ultimately the decision to synchronously throw or not is up to you, and you will likely find people who argue either side. The important thing is to document the behavior and maintain consistency in the behavior.

My opinion on the matter is that your second option - passing the error into the callback - seems more elegant. Otherwise you end up with code that looks like this:

try {
    getUserById(7, function (response) {
       if (response.isSuccess) {
           //Success case
       } else {
           //Failure case
       }
    });
} catch (error) {
    //Other failure case
}

The control flow here is slightly confusing.

It seems like it would be better to have a single if / else if / else structure in the callback and forgo the surrounding try / catch.

다른 팁

This is largely a matter of opinion. Whatever you do, do it consistently, and document it clearly.

One objective piece of information I can give you is that this was the subject of much discussion in the design of JavaScript's async functions, which as you may know implicitly return promises for their work. You may also know that the part of an async function prior to the first await or return is synchronous; it only becomes asynchronous at the point it awaits or returns.

TC39 decided in the end that even errors thrown in the synchronous part of an async function should reject its promise rather than raising a synchronous error. For example:

async function someAsyncStuff() {
    return 21;
}

async function example() {
    console.log("synchronous part of function");
    throw new Error("failed");
    const x = await someAsyncStuff();
    return x * 2;
}
try {
    console.log("before call");
    example().catch(e => { console.log("asynchronous:", e.message); });
    console.log("after call");
} catch (e) {
    console.log("synchronous:", e.message);
}

There you can see that even though throw new Error("failed") is in the synchronous part of the function, it rejects the promise rather than raising a synchronous error.

That's true even for things that happen before the first statement in the function body, such as determining the default value for a missing function parameter:

async function someAsyncStuff() {
    return 21;
}

async function example(p = blah()) {
    console.log("synchronous part of function");
    throw new Error("failed");
    const x = await Promise.resolve(42);
    return x;
}
try {
    console.log("before call");
    example().catch(e => { console.log("asynchronous:", e.message); });
    console.log("after call");
} catch (e) {
    console.log("synchronous:", e.message);
}

That fails because it tries to call blah, which doesn't exist, when it runs the code to get the default value for the p parameter I didn't supply in the call. As you can see, even that rejects the promise rather than throwing a synchronous error.

TC39 could have gone the other way, and had the synchronous part raise a synchronous error, like this non-async function does:

async function someAsyncStuff() {
    return 21;
}

function example() {
    console.log("synchronous part of function");
    throw new Error("failed");
    return someAsyncStuff().then(x => x * 2);
}
try {
    console.log("before call");
    example().catch(e => { console.log("asynchronous:", e.message); });
    console.log("after call");
} catch (e) {
    console.log("synchronous:", e.message);
}

But they decided, after discussion, on consistent promise rejection instead.

So that's one concrete piece of information to consider in your decision about how you should handle this in your own non-async functions that do asynchronous work.

How important is it that an async function should always behave in an async manner, particularly for error conditions?

Very important.

Is it OK to throw if you know that the program is not in a suitable state for the async operation to proceed?

Yes, I personally think it is OK when that is a very different error from any asynchronously produced ones, and needs to be handled separately anyway.

If some userids are known to be invalid because they're not numeric, and some are will be rejected on the server (eg because they're already taken) you should consistently make an (async!) callback for both cases. If the async errors would only arise from network problems etc, you might signal them differently.

You always may throw when an "unexpected" error arises. If you demand valid userids, you might throw on invalid ones. If you want to anticipate invalid ones and expect the caller to handle them, you should use a "unified" error route which would be the callback/rejected promise for an async function.

And to repeat @Timothy: You should always document the behavior and maintain consistency in the behavior.

Callback APIs ideally shouldn't throw but they do throw because it's very hard to avoid since you have to have try catch literally everywhere. Remember that throwing error explicitly by throw is not required for a function to throw. Another thing that adds to this is that the user callback can easily throw too, for example calling JSON.parse without try catch.

So this is what the code would look like that behaves according to these ideals:

readFile("file.json", function(err, val) {
    if (err) {
        console.error("unable to read file");
    }
    else {
        try {
            val = JSON.parse(val);
            console.log(val.success);
        }
        catch(e) {
            console.error("invalid json in file");
        }
    }
});

Having to use 2 different error handling mechanisms is really inconvenient, so if you don't want your program to be a fragile house of cards (by not writing any try catch ever) you should use promises which unify all exception handling under a single mechanism:

readFile("file.json").then(JSON.parse).then(function(val) {
    console.log(val.success);
})
.catch(SyntaxError, function(e) {
    console.error("invalid json in file");
})
.catch(function(e){
    console.error("unable to read file")
})

Ideally you would have a multi-layer architecture like controllers, services, etc. If you do validations in services, throw immediately and have a catch block in your controller to catch the error format it and send an appropriate http error code. This way you can centralize all bad request handling logic. If you handle each case youll end up writing more code. But thats just how I would do it. Depends on your use case

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top