user6004404 user6004404 - 5 months ago 16
JSON Question

Try Except block for multiple validation errors

try:
if isDateValid(date) == false:
raise ValidationError('invalid date')
if usernameValid(user) == false:
raise ValidationError('invalid username')
except ValidationError:
data = json.dumps({'status': 'Enter a valid date'})
data = json.dumps({'status': 'Enter a valid username'})
return HttpResponseBadRequest(data, content_type='application/json')`


How can I make data = the correct message depending on where the error is thrown or the message passed?

Answer

Access the exception instance you are raising:

try: 
    if isDateValid(date) == false:
        raise ValidationError('invalid date')
    if usernameValid(user) == false:
        raise ValidationError('invalid username')
except ValidationError as e:
    data = json.dumps({'status': str(e)})
    return HttpResponseBadRequest(data, content_type='application/json')

Well, the above will produce 'status': 'invalid date'. If you want to give the message 'enter a valid date' you have to see which message got passed:

except ValidationError as e:
    msg = 'Enter a valid '
    if str(e).endswith('date'):
        msg += 'date'
    else:
        msg += 'username'
    data = json.dumps({'status': msg})
    return HttpResponseBadRequest(data, content_type='application/json')

Or even simpler:

except ValidationError as e:
    msg = 'Enter a valid ' + str(e)[len('invalid '):]
    data = json.dumps({'status': msg})
    return HttpResponseBadRequest(data, content_type='application/json')

Personally you should ask yourself whether you could just use two different subclasses of ValidationError for the two different conditions. You could have InvalidUsernameError and InvalidDateError and catch them separately. This would surely produce a much more robust solution (you aren't relying on the exact text passed to the raised exception), even though going too deep with class hierarchies isn't generally a good thing.