Format API error messages (#1997)

This commit is contained in:
Joakim Sørensen 2020-08-30 17:53:10 +02:00 committed by GitHub
parent 928a4d8dce
commit f32d17d924
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 34 additions and 8 deletions

View File

@ -552,7 +552,7 @@ class Addon(AddonModel):
await self.instance.run()
except DockerAPIError as err:
self.state = AddonState.ERROR
raise AddonsError() from err
raise AddonsError(err) from None
else:
self.state = AddonState.STARTED

View File

@ -1,6 +1,5 @@
"""Init file for Supervisor util for RESTful API."""
import json
import logging
from typing import Any, Dict, List, Optional
from aiohttp import web
@ -19,8 +18,7 @@ from ..const import (
RESULT_OK,
)
from ..exceptions import APIError, APIForbidden, HassioError
_LOGGER: logging.Logger = logging.getLogger(__name__)
from ..utils.log_format import format_message
def excract_supervisor_token(request: web.Request) -> Optional[str]:
@ -61,8 +59,10 @@ def api_process(method):
answer = await method(api, *args, **kwargs)
except (APIError, APIForbidden) as err:
return api_return_error(message=str(err))
except HassioError:
return api_return_error(message="Unknown Error, see logs")
except HassioError as err:
return api_return_error(
message=str(err) if err else "Unknown Error, see logs"
)
if isinstance(answer, dict):
return api_return_ok(data=answer)
@ -103,7 +103,7 @@ def api_process_raw(content):
def api_return_error(message: Optional[str] = None) -> web.Response:
"""Return an API error message."""
return web.json_response(
{JSON_RESULT: RESULT_ERROR, JSON_MESSAGE: message}, status=400
{JSON_RESULT: RESULT_ERROR, JSON_MESSAGE: format_message(message)}, status=400
)

View File

@ -149,7 +149,7 @@ class DockerAPI:
container.start()
except (docker.errors.DockerException, requests.RequestException) as err:
_LOGGER.error("Can't start %s: %s", name, err)
raise DockerAPIError() from err
raise DockerAPIError(err) from None
# Update metadata
with suppress(docker.errors.DockerException, requests.RequestException):

View File

@ -0,0 +1,15 @@
"""Custom log messages."""
import re
RE_BIND_FAILED = re.compile(r".*Bind for.*:(\d*) failed: port is already allocated.*")
def format_message(message: str) -> str:
"""Return a formated message if it's known."""
match = RE_BIND_FAILED.match(message)
if match:
return (
f"Port '{match.group(1)}' is already in use by something else on the host."
)
return message

View File

@ -0,0 +1,11 @@
"""Tests for message formater."""
from supervisor.utils.log_format import format_message
def test_format_message():
"""Tests for message formater."""
message = '500 Server Error: Internal Server Error: Bind for 0.0.0.0:80 failed: port is already allocated")'
assert (
format_message(message)
== "Port '80' is already in use by something else on the host."
)