49

In this function that handles a REST API call, any of the called functions to handle parts of the request might throw an error to signal that an error code should be sent as response. However, the function itself might also discover an error, at which point it should jump into the exception handling block.

static async handleRequest(req) {
    try {
        let isAllowed = await checkIfIsAllowed(req);
        if (!isAllowed) {
            throw new ForbiddenException("You're not allowed to do that.");
        }
        let result = await doSomething(req); // can also raise exceptions
        sendResult(result);
    } catch(err) {
        sendErrorCode(err);
    }
}

Webstorm will underline the throw with the following message: 'throw' of exception caught locally. This inspection reports any instances of JavaScript throw statements whose exceptions are always caught by containing try statements. Using throw statements as a "goto" to change the local flow of control is likely to be confusing.

However, I'm not sure how to refactor the code to improve the situation.

I could copypaste the code from the catch block into the if check, but I believe this would make my code less readable and harder to maintain.

I could write a new function that does the isAllowed check and throws an exception if it doesn't succeed, but that seems to be sidestepping the issue, rather than fixing a design problem that Webstorm is supposedly reporting.

Are we using exceptions in a bad way, and that's why we're encountering this problem, or is the Webstorm error simply misguiding and should be disabled?

cib
  • 1,544
  • 1
  • 16
  • 20
  • @matchish Hey - just noticed this bounty. I'm unsure what part of my answer you feel breaks DRY principles? The only thing I can think is the `sendErrorCode` - but it's not being repeated verbatim; in one place it's sending a very specific error from this block of code, in the more general `catch` it's sending a more general error that hasn't been coded for...? – James Thorpe Jan 17 '19 at 15:23

7 Answers7

45

You're checking for something and throwing an exception if isAllowed fails, but you know what to do in that situation - call sendErrorCode. You should throw exceptions to external callers if you don't know how to handle the situation - ie in exceptional circumstances.

In this case you already have a defined process of what to do if this happens - just use it directly without the indirect throw/catch:

static async handleRequest(req) {
    try {
        let isAllowed = await checkIfIsAllowed(req);
        if (!isAllowed) {
            sendErrorCode("You're not allowed to do that.");
            return;
        }
        let result = await doSomething(req); // can also raise exceptions
        sendResult(result);
    } catch(err) {
        sendErrorCode(err);
    }
}

I could copypaste the code from the catch block into the ifcheck, but I believe this would make my code less readable and harder to maintain.

On the contrary, as above, I would expect this to be the way to handle this situation.

James Thorpe
  • 28,613
  • 5
  • 64
  • 82
  • 3
    "You should throw exceptions to external callers if you don't know how to handle the situation - ie in exceptional circumstances." If that's true, that explains the issue. However, that means we're using exceptions wrong in the entire project, not just this function. Since there are no other answers, I'll accept this one. – cib Nov 02 '17 at 09:09
  • James, I agree with the answer, but a friend sent me this: https://dev.to/nedsoft/central-error-handling-in-express-3aej What do you think? – fsljfke Jul 26 '20 at 21:57
  • If all you have to do is "sendErrorCode()" and then return, this is fine. However, if you have to do several actions in response to dealing with or cleaning up from an error, then you end up duplicating code. It gets even worse if you have multiple places in your try block where you can detect an internal error. If you have to do additional work after the catch block regardless of error or not, then you have no way of getting there if you return in the try block. – wojtow Jan 02 '21 at 05:41
  • @wojtow your scenarios sound like they could be dealt with via refactoring... – James Thorpe Jan 02 '21 at 07:45
31

Contrary to James Thorpe's opinion, I slightly prefer the pattern of throwing. I don't see any compelling reason to treat local errors in the try block any differently from errors that bubble up from deeper in the call stack... just throw them. In my opinion, this is a better application of consistency.

Because this pattern is more consistent, it naturally lends itself better to refactoring when you want to extract logic in the try block to another function that is perhaps in another module/file.

// main.js
try {
  if (!data) throw Error('missing data')
} catch (error) {
  handleError(error)
}

// Refactor...

// validate.js
function checkData(data) {
  if (!data) throw Error('missing data')
}

// main.js
try {
  checkData(data)
} catch (error) {
  handleError(error)
}

If instead of throwing in the try block you handle the error, then the logic has to change if you refactor it outside of the try block.

In addition, handling the error has the drawback of making you remember to return early so that the try block doesn't continue to execute logic after the error is encountered. This can be quite easy to forget.

try {
  if (!data) {
    handleError(error)
    return // if you forget this, you might execute code you didn't mean to. this isn't a problem with throw.
  }
  // more logic down here
} catch (error) {
  handleError(error)
}

If you're concerned about which method is more performant, you shouldn't be. Handling the error is technically more performant, but the difference between the two is absolutely trivial.

Consider the possibility that WebStorm is a bit too opinionated here. ESLint doesn't even have a rule for this. Either pattern is completely valid.

J. Munson
  • 799
  • 8
  • 17
10

Since this is not a blocking error, but only an IDE recommendation, then the question should be viewed from two sides.

The first side is performance. If this is a bottleneck and it is potentially possible to use it with compilation or when transferring to new (not yet released) versions of nodejs, the presence of repetitions is not always a bad solution. It seems that the IDE hints precisely in this case and that such a design can lead to poor optimization in some cases.

The second side is the code design. If it will make the code more readable and simplify the work for other developers - keep it. From this point of view, solutions have already been proposed above.

SlowSuperman
  • 348
  • 1
  • 6
  • 13
6

Return a promise reject instead of throwing error in the try block

  try {
    const isAllowed = await checkIfIsAllowed(request);

    if (!isAllowed) {
      return Promise.reject(Error("You're not allowed to do that."));
    }

    const result = await doSomething(request);

    sendResult(result);
  } catch (error) {
    throw error;
  }
2

There are good answers to the question "Why not use exceptions as normal flow control?" here.

The reason not to throw an exception that you will catch locally is that you locally know how to handle that situation, so it is, by definition, not exceptional.

@James Thorpe's answer looks good to me, but @matchish feels it violates DRY. I say that in general, it does not. DRY, which stands for Don't Repeat Yourself, is defined by the people who coined the phrase as "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system". As applied to writing software code, it is about not repeating complex code.

Practically any code that is said to violate DRY is said to be "fixed" by extracting the repeated code into a function and then calling that function from the places it was previously repeated. Having multiple parts of your code call sendErrorCode is the solution to fixing a DRY problem. All of the knowledge of what to do with the error is in one definitive place, namely the sendErrorCode function.

I would modify @James Thorpe's answer slightly, but it is more of a quibble than a real criticism, which is that sendErrorCode should be receiving exception objects or strings but not both:

static async handleRequest(req) {
    try {
        let isAllowed = await checkIfIsAllowed(req);
        if (!isAllowed) {
            sendErrorCode(new ForbiddenException("You're not allowed to do that."));
            return;
        }
        let result = await doSomething(req); // can also raise exceptions
        sendResult(result);
    } catch(err) {
        sendErrorCode(err);
    }
}

The larger question is what is the likelihood of the error and is it appropriate to treat !isAllowed as an exception. Exceptions are meant to handle unusual or unpredictable situations. I would expect !isAllowed to be a normal occurrence that should be handled with logic specific to that situation, unlike, say, a sudden inability to query the database that has the answer to the isAllowed question.

@matchish's proposed solution changes the contract of doSomethingOnAllowedRequest from something that will never throw an exception to something that will routinely throw an exception, placing the burden of exception handling on all of its callers. This is likely to cause a violation of DRY by causing multiple callers to have repetitions of the same error handling code, so in the abstract I do not like it. In practice, it would depend on the overall situation, such as how many callers are there and do they, in fact, share the same response to errors.

Old Pro
  • 22,324
  • 4
  • 52
  • 96
  • What if you need to log errors? You should modify two lines of code, that's why I think it's not DRY. – matchish Jan 21 '19 at 08:11
  • You write !isAllowed is not unpredictable situation, but I see ForbiddenException in your code. handleRequest created for to do something useful, and when we can't do it I think it's normal to throw the exception. For me sendErrorCode looks like throwing an exception to frontend – matchish Jan 21 '19 at 08:20
  • @matchish _"What if you need to log errors?"_ The `!isAllowed` isn't neccessarily an error/exception as far as this code is concerned (it's a handled use case), so no need to log it. At this point though, we're debating code for which we don't know the underlying semantics and use case of such things, and it's far removed from the original purpose of this Q&A. – James Thorpe Jan 21 '19 at 09:07
  • I'm talking not about logging, it can be anything else. You have two pieces of code that will need to be changed if you need not only sendErrorCode. IMO It's not DRY – matchish Jan 21 '19 at 09:38
  • @matchish if you need to log errors, you can add error logging to `sendErrorCode`. I have `ForbiddenException` in my code because you had it in your code and it appears `sendErrorCode` expects an exception object, not a string. What if `handleRequest` has 10 callers? Then you have to repeat the exception handling 10 times if you do not do it in `handleRequest`. – Old Pro Jan 22 '19 at 22:51
  • @OldPro If you logging errors in sendErrorCode you violate SRP principle – matchish Jan 23 '19 at 05:46
  • 1
    @matchish how is logging errors in what is uniquely error handling code (`sendErrorCode`) more of a violation of SRP than logging errors in code whose job is to handle requests? – Old Pro Jan 23 '19 at 07:14
1

Answer of James Thorpe has one disadvantage on my opinion. It's not DRY, in both cases when you call sendError you handle Exceptions. Let's imagine we have many lines of code with logic like this where Exception can be thrown. I think it can be better.

This is my solution

async function doSomethingOnAllowedRequest(req) {
    let isAllowed = await checkIfIsAllowed(req);
    if (!isAllowed) {
       throw new ForbiddenException("You're not allowed to do that.");
    }
    doSomething(req);
}
static async handleRequest(req) {
    try {
        let result = await doSomethingOnAllowedRequest(req);
        sendResult(result);
    } catch(err) {
        sendErrorCode(err);
    }
}
matchish
  • 1,671
  • 3
  • 14
  • 28
  • It is DRY, in that if you're not allowed to do the action, you're sending a very specific error message. The catch is there for all other exceptions. IMO you're just moving the "don't use exceptions for flow logic control" into another method here. Throwing an exception is not cheap (computationally) compared to not throwing either - if you can avoid doing so, far better to not do it. – James Thorpe Jan 17 '19 at 16:49
  • I prefer readability to performance. IMO It's not just moving. doSomething also can throw Exception, but I don't think we can say we use exception for flow control in this case. You can doSomething only on allowed request if it not allowed you should throw the exception. – matchish Jan 17 '19 at 17:52
  • What about using `try...catch...finally`? I was using such a statement to release some resources at the `finally` block, and several calls in the `try` block could throw an exception as well. If I had to interrupt the `try` flow locally and release those resources, I can not come with a more readable solution than just throwing there. – David Jun 14 '19 at 16:02
-5

This could give you some tips, maybe that can be the cause(not sure if relevant). Catch statement does not catch thrown error

" The reason why your try catch block is failing is because an ajax request is asynchronous. The try catch block will execute before the Ajax call and send the request itself, but the error is thrown when the result is returned, AT A LATER POINT IN TIME.

When the try catch block is executed, there is no error. When the error is thrown, there is no try catch. If you need try catch for ajax requests, always put ajax try catch blocks inside the success callback, NEVER outside of it."