Repository: halcy/Mastodon.py

Issue:
"string indices must be integers" when handling an error

```
TypeError('string indices must be integers',)

Traceback (most recent call last):
...
  File "/home/codl/forget/libforget/mastodon.py", line 165, in refresh_posts
    status = api.status(post.mastodon_id)
  File "</home/codl/.local/share/virtualenvs/forget-jXTy0Bc2/lib/python3.6/site-packages/decorator.py:decorator-gen-10>", line 2, in status
  File "/home/codl/.local/share/virtualenvs/forget-jXTy0Bc2/lib/python3.6/site-packages/mastodon/Mastodon.py", line 77, in wrapper
    return function(self, *args, **kwargs)
  File "/home/codl/.local/share/virtualenvs/forget-jXTy0Bc2/lib/python3.6/site-packages/mastodon/Mastodon.py", line 620, in status
    return self.__api_request('GET', url)
  File "/home/codl/.local/share/virtualenvs/forget-jXTy0Bc2/lib/python3.6/site-packages/mastodon/Mastodon.py", line 2202, in __api_request
    error_msg = response['error']
```

this is the code in question ↓

https://github.com/halcy/Mastodon.py/blob/55ec333562d49ac8ac65000e0c01ae88255576f1/mastodon/Mastodon.py#L2197-L2204

i think i wrote this, haha

my best guess for how this could happen is if the error page returns a bare json string with the word "error" in it. i think this was on a pleroma instance but i couldnt look into it further at the time

Discussion:

Patch:
diff --git a/mastodon/Mastodon.py b/mastodon/Mastodon.py
index fc585ba..37e35b7 100644
--- a/mastodon/Mastodon.py
+++ b/mastodon/Mastodon.py
@@ -2214,9 +2214,12 @@ class Mastodon:
             if not response_object.ok:
                 try:
                     response = response_object.json(object_hook=self.__json_hooks)
-                    if not isinstance(response, dict) or 'error' not in response:
+                    if isinstance(response, dict) and 'error' in response:
+                        error_msg = response['error']
+                    elif isinstance(response, str):
+                        error_msg = response
+                    else:
                         error_msg = None
-                    error_msg = response['error']
                 except ValueError:
                     error_msg = None
 


Test patch:
diff --git a/tests/test_errors.py b/tests/test_errors.py
new file mode 100644
index 0000000..7329507
--- /dev/null
+++ b/tests/test_errors.py
@@ -0,0 +1,20 @@
+import pytest
+from mastodon.Mastodon import MastodonAPIError
+
+try:
+    from mock import MagicMock
+except ImportError:
+    from unittest.mock import MagicMock
+
+def test_nonstandard_errors(api):
+    response = MagicMock()
+    response.json = MagicMock(return_value=
+            "I am a non-standard instance and this error is a plain string.")
+    response.ok = False
+    session = MagicMock()
+    session.request = MagicMock(return_value=response)
+
+    api.session = session
+    with pytest.raises(MastodonAPIError):
+        api.instance()
+