mercredi 12 juin 2019

Handling Errors with Codes or Exceptions

There are a lot of articles about exceptions vs error codes in various layers. We have a large API which returns errors in the form of errorCode,errorMessage to the calling client. The code below is just a small extract of whats going on.

public async Task<OrderResult> CompleteOrder()
{
    var response = new OrderResult();
    var order = await CurrentOrder();

    var processResult = await ProcessOrder(order);
    if (!processResult.IsComplete)
    {
        response.Errors.AddRange(processResult.Errors);
        return response;
    }

    var emailResult = await Email(order);
    if (!emailResult.Sent)
    {
        response.Errors.AddRange(emailResult.Errors);
        return response;
    }
    //Lots of these calls each processing different results if success or not
    var anotherResult = await AnotherAction(order);
    if (!anotherResult.Success)
    {
        response.Errors.AddRange(anotherResult.Errors);
        return response;
    }

    //All good carry on

    return response;
}

So basically above is really almost a repeat of if/then but with different logic depending on result and we return errorCodes as we know what the error is when it occurs.

As this is an api the call would see something like {errorCode:12,errorMessage:'There was a problem processing'} which is what we want.

As these methods are becoming larger the if(error) return statements are repeated more often.

Questions

Would it be worth to continue with this practice or maybe have each method like ProcessOrder/Email etc throw custom exception containing the errorcode and message and just wrap everything up in try/catch.

Example

try{
//call actions
}
catch(CustomEx e)
{
response.Errors.AddRange(e.Errors);
}
if(response.Errors.Count>0)
return response;

I believe the code is very readable at each stage and clear the way its done, but am open to other ways of doing these calls without repeating.

Any suggestions would be appreciated.

Aucun commentaire:

Enregistrer un commentaire