2
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?

1
  • Why are you using try/except at all? You could just set the data var directly in those if statements. And that would solve your message customization q. Commented Jun 28, 2016 at 16:47

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.