Skip to content

Commit 7979ba5

Browse files
committed
add handler_assertion_error and test ErrHandler
1 parent ffb0b9b commit 7979ba5

File tree

2 files changed

+53
-4
lines changed

2 files changed

+53
-4
lines changed

hobbit_core/flask_hobbit/err_handler.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,25 @@ def handler_sqlalchemy_orm_exc(cls, e):
3333
code, message, detail = 500, RESP_MSGS[500], repr(e)
3434

3535
if isinstance(e, orm_exc.NoResultFound):
36-
code, message, detail = 404, '源数据未找到', repr(e)
36+
code, message, detail = 404, u'源数据未找到', repr(e)
3737

3838
return Result(gen_response(code, message, detail), status=code)
3939

40+
@classmethod
41+
def handler_assertion_error(cls, e):
42+
code, message, detail = 422, str(e), repr(e)
43+
return Result(gen_response(code, message, detail), status=code)
44+
4045
@classmethod
4146
def handler_others(cls, e):
4247
traceback.print_exc()
43-
return ServerErrorResult(500, detail=repr(e))
48+
return ServerErrorResult(code=500, detail=repr(e))
4449

4550
@classmethod
4651
def handler(cls, e):
47-
exc = 'others' if not hasattr(e, '__module__') else \
48-
e.__module__.replace('.', '_')
52+
exc = 'others'
53+
if hasattr(e, '__module__'):
54+
exc = e.__module__.replace('.', '_')
55+
elif isinstance(e, AssertionError):
56+
exc = 'assertion_error'
4957
return getattr(cls, 'handler_{}'.format(exc), cls.handler_others)(e)

tests/test_err_handler.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import json
2+
3+
from sqlalchemy.orm import exc as orm_exc
4+
from werkzeug import exceptions as wkz_exc
5+
6+
from hobbit_core.flask_hobbit.err_handler import ErrHandler
7+
8+
from . import BaseTest
9+
10+
11+
class TestErrHandler(BaseTest):
12+
13+
def test_assertion_error(self):
14+
resp = ErrHandler.handler(AssertionError('message'))
15+
assert resp.status_code == 422
16+
data = json.loads(resp.get_data())
17+
assert data['message'] == 'message'
18+
19+
def test_sqlalchemy_orm_exc(self):
20+
resp = ErrHandler.handler(orm_exc.NoResultFound())
21+
assert resp.status_code == 404
22+
data = json.loads(resp.get_data())
23+
assert data['message'] == u'源数据未找到'
24+
25+
resp = ErrHandler.handler(orm_exc.UnmappedError())
26+
assert resp.status_code == 500
27+
data = json.loads(resp.get_data())
28+
assert data['message'] == u'服务器内部错误'
29+
30+
def test_werkzeug_exceptions(self):
31+
resp = ErrHandler.handler(wkz_exc.Unauthorized())
32+
assert resp.status_code == 401
33+
data = json.loads(resp.get_data())
34+
assert data['message'] == u'未登录'
35+
36+
def test_others(self):
37+
resp = ErrHandler.handler(Exception('msg'))
38+
assert resp.status_code == 500
39+
data = json.loads(resp.get_data())
40+
assert data['message'] == u'服务器内部错误'
41+
assert data['detail'] == "Exception('msg')"

0 commit comments

Comments
 (0)