server/rest: simplify error handling flow
This commit is contained in:
parent
4340b4d9b2
commit
ef079121a9
|
@ -65,38 +65,37 @@ def _create_context(env):
|
||||||
|
|
||||||
def application(env, start_response):
|
def application(env, start_response):
|
||||||
try:
|
try:
|
||||||
try:
|
ctx = _create_context(env)
|
||||||
ctx = _create_context(env)
|
if 'application/json' not in ctx.get_header('Accept'):
|
||||||
if 'application/json' not in ctx.get_header('Accept'):
|
raise errors.HttpNotAcceptable(
|
||||||
raise errors.HttpNotAcceptable(
|
'ValidationError',
|
||||||
'ValidationError',
|
'This API only supports JSON responses.')
|
||||||
'This API only supports JSON responses.')
|
|
||||||
|
|
||||||
for url, allowed_methods in routes.routes.items():
|
for url, allowed_methods in routes.routes.items():
|
||||||
match = re.fullmatch(url, ctx.url)
|
match = re.fullmatch(url, ctx.url)
|
||||||
if not match:
|
if match:
|
||||||
continue
|
|
||||||
if ctx.method not in allowed_methods:
|
if ctx.method not in allowed_methods:
|
||||||
raise errors.HttpMethodNotAllowed(
|
raise errors.HttpMethodNotAllowed(
|
||||||
'ValidationError',
|
'ValidationError',
|
||||||
'Allowed methods: %r' % allowed_methods)
|
'Allowed methods: %r' % allowed_methods)
|
||||||
|
|
||||||
for hook in middleware.pre_hooks:
|
|
||||||
hook(ctx)
|
|
||||||
handler = allowed_methods[ctx.method]
|
handler = allowed_methods[ctx.method]
|
||||||
try:
|
break
|
||||||
response = handler(ctx, match.groupdict())
|
else:
|
||||||
finally:
|
|
||||||
for hook in middleware.post_hooks:
|
|
||||||
hook(ctx)
|
|
||||||
|
|
||||||
start_response('200', [('content-type', 'application/json')])
|
|
||||||
return (_dump_json(response).encode('utf-8'),)
|
|
||||||
|
|
||||||
raise errors.HttpNotFound(
|
raise errors.HttpNotFound(
|
||||||
'ValidationError',
|
'ValidationError',
|
||||||
'Requested path ' + ctx.url + ' was not found.')
|
'Requested path ' + ctx.url + ' was not found.')
|
||||||
|
|
||||||
|
try:
|
||||||
|
for hook in middleware.pre_hooks:
|
||||||
|
hook(ctx)
|
||||||
|
try:
|
||||||
|
response = handler(ctx, match.groupdict())
|
||||||
|
finally:
|
||||||
|
for hook in middleware.post_hooks:
|
||||||
|
hook(ctx)
|
||||||
|
start_response('200', [('content-type', 'application/json')])
|
||||||
|
return (_dump_json(response).encode('utf-8'),)
|
||||||
|
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
for exception_type, handler in errors.error_handlers.items():
|
for exception_type, handler in errors.error_handlers.items():
|
||||||
if isinstance(ex, exception_type):
|
if isinstance(ex, exception_type):
|
||||||
|
|
Loading…
Reference in New Issue