title: how to improve exception handling in python/django
body: <p>This is an example of my exception handling in a django project:</p>
  
  <pre><code>def boxinfo(request, url: str):
      box = get_box(url)
      try:
          box.connect()
      except requests.exceptions.ConnectionError as e:
          context = {'error_message': 'Could not connect to your box because the host is unknown.'}
          return render(request, 'box/error.html', context)
      except requests.exceptions.RequestException as e:
          context = {'error_message': 'Could not connect to your box because of an unknown error.'}
          return render(request, 'box/error.html', context)
  </code></pre>
  
  <ul>
  <li>There is only two excepts now, but it should be more for the several request exceptions. But already the view method is bloated up by this. Is there a way to forward the except handling to a separate error method?</li>
  <li>There is also the problem, that I need here to call the render message for each except, I would like to avoid that. </li>
  <li>And here I also repeat for each except "could not connect to your box because", that should be set once when there appeared any exception.</li>
  </ul>
  
  <p>I can solve it by something like this:</p>
  
  <pre><code>try:
      box.connect()
  except Exception as e:
      return error_handling(request, e)
  </code></pre>
  
  <p>-</p>
  
  <pre><code>def error_handling(request, e):
      if type(e).__name__ == requests.exceptions.ConnectionError.__name__:
          context = {'error_message': 'Could not connect to your box because the host is unknown.'}
      elif type(e).__name__ == requests.exceptions.RequestException.__name__:
          context = {'error_message': 'Could not connect to your box because of an unknown error.'}
      else:
          context = {'error_message': 'There was an unkown error, sorry.'}
      return render(request, 'box/error.html', context)
  </code></pre>
  
  <p>and I could of course improve the error message thing then. But overall, is it a pythonic way to handle exceptions with <code>if/else</code>? For example I could not catch <code>RequestException</code> here if <code>ConnectionError</code> is thrown, so I would need to catch each requests error, that looks more like an ugly fiddling...</p>