Skip to content

Commit 102361b

Browse files
Merge pull request #15 from TeskaLabs/Feature/Introduce-exceptions
Introduce exception : PathError, FormatError
2 parents 173e305 + 7fdb154 commit 102361b

File tree

6 files changed

+82
-30
lines changed

6 files changed

+82
-30
lines changed

asabiris/exceptions.py

+35
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,37 @@
11
class SMTPDeliverError(Exception):
22
pass
3+
4+
5+
class PathError(Exception):
6+
"""
7+
8+
Equivalent to HTTP 404 Not-Found.
9+
"""
10+
11+
def __init__(self, message=None, *args, path=None):
12+
self.Path = path
13+
if message is not None:
14+
super().__init__(message, *args)
15+
elif path is not None:
16+
message = "Invalid path {!r}.".format(path)
17+
super().__init__(message, *args)
18+
else:
19+
super().__init__(message, *args)
20+
21+
22+
class FormatError(Exception):
23+
"""
24+
25+
Equivalent to HTTP 400 Bad-request.
26+
"""
27+
28+
def __init__(self, message=None, *args, format=None):
29+
self.Format = format
30+
if message is not None:
31+
super().__init__(message, *args)
32+
elif format is not None:
33+
message = "Unsupported template format {!r}.".format(format)
34+
super().__init__(message, *args)
35+
else:
36+
super().__init__(message, *args)
37+

asabiris/handlers/webhandler.py

+18-3
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from ..schemas.emailschema import email_schema
1111
from ..schemas.slackschema import slack_schema
1212

13-
from ..exceptions import SMTPDeliverError
13+
from ..exceptions import SMTPDeliverError, PathError, FormatError
1414

1515
#
1616

@@ -112,6 +112,12 @@ async def send_email(self, request, *, json_data):
112112
except SMTPDeliverError:
113113
raise aiohttp.web.HTTPServiceUnavailable(text="SMTP error")
114114

115+
except PathError as e:
116+
raise aiohttp.web.HTTPNotFound(text="{}".format(e))
117+
118+
except FormatError as e:
119+
raise aiohttp.web.HTTPBadRequest(text="{}".format(e))
120+
115121
# More specific exception handling goes here so that the service provides nice output
116122
return asab.web.rest.json_response(request, {"result": "OK"})
117123

@@ -142,6 +148,12 @@ async def send_alert(self, request, *, json_data):
142148
except jinja2.exceptions.UndefinedError as e:
143149
raise aiohttp.web.HTTPBadRequest(text="Jinja2 error: {}".format(e))
144150

151+
except PathError as e:
152+
raise aiohttp.web.HTTPNotFound(text="{}".format(e))
153+
154+
except FormatError as e:
155+
raise aiohttp.web.HTTPBadRequest(text="{}".format(e))
156+
145157
# More specific exception handling goes here so that the service provides nice output
146158

147159
return asab.web.rest.json_response(request, {"result": "OK"})
@@ -175,7 +187,10 @@ async def render(self, request):
175187
template_data = await request.json()
176188

177189
# Render a body
178-
html = await self.App.RenderReportOrchestrator.render(template, template_data)
190+
try:
191+
html = await self.App.RenderReportOrchestrator.render(template, template_data)
192+
except PathError as e:
193+
raise aiohttp.web.HTTPNotFound(text="{}".format(e))
179194

180195
# get pdf from html if present.
181196
if fmt == 'pdf':
@@ -184,7 +199,7 @@ async def render(self, request):
184199
elif fmt == 'html':
185200
content_type = "text/html"
186201
else:
187-
raise ValueError("Invalid/unknown format: '{}'".format(fmt))
202+
raise aiohttp.web.HTTPBadRequest(text="Invalid/unknown conversion format: '{}'".format(fmt))
188203

189204
return aiohttp.web.Response(
190205
content_type=content_type,

asabiris/orchestration/render.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import os
22
import logging
33

4+
from .. exceptions import PathError, FormatError
45
from .. import utils
56

67
#
@@ -26,8 +27,8 @@ async def render(self, template, params):
2627
# - if absolute path is used, check it start with "/Templates"
2728
# - if it is not absolute path, it is file name - assume it's a file in Templates folder
2829
# templates must be stores in /Templates/General
29-
if not template.startswith("/Templates/General"):
30-
raise ValueError("Template must be stored in /Templates/General directory")
30+
if not template.startswith("/Templates/General/"):
31+
raise PathError(path=template)
3132

3233
html = await self.JinjaService.format(template, params)
3334
_, extension = os.path.splitext(template)
@@ -42,4 +43,4 @@ async def render(self, template, params):
4243

4344
return html
4445

45-
raise RuntimeError("Failed to render templates. Reason: Unknown extention '{}'".format(extension))
46+
raise FormatError(format=extension)

asabiris/orchestration/sendemail.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import logging
55

66
from .. import utils
7-
7+
from .. exceptions import PathError, FormatError
88
#
99

1010
L = logging.getLogger(__name__)
@@ -70,8 +70,8 @@ async def send_email(
7070
if template is not None:
7171
params = a.get('params', {})
7272
# templates must be stores in /Templates/Emails
73-
if not template.startswith("/Templates/Email"):
74-
raise ValueError("Template must be stored in /Templates/Email directory")
73+
if not template.startswith("/Templates/Email/"):
74+
raise PathError(path=template)
7575

7676
# get file-name of the attachment
7777
file_name = self.get_file_name(a)
@@ -86,7 +86,7 @@ async def send_email(
8686
result = jinja_output.encode("utf-8")
8787
content_type = "text/html"
8888
else:
89-
raise ValueError("Invalid/unknown format '{}'".format(fmt))
89+
raise FormatError(format=fmt)
9090

9191
atts.append((result, content_type, file_name))
9292
continue
@@ -122,8 +122,8 @@ async def render(self, template, params):
122122
jinja_output will be used for extracting subject.
123123
"""
124124
# templates must be stores in /Templates/Emails
125-
if not template.startswith("/Templates/Email"):
126-
raise ValueError("Template must be stored in /Templates/Email directory")
125+
if not template.startswith("/Templates/Email/"):
126+
raise PathError(path=template)
127127

128128
try:
129129
jinja_output = await self.JinjaService.format(template, params)
@@ -144,7 +144,7 @@ async def render(self, template, params):
144144
return html_output, subject
145145

146146
else:
147-
raise RuntimeError("Failed to render templates. Reason: Unknown extention '{}'".format(extension))
147+
raise FormatError(format=extension)
148148

149149
def get_file_name(self, attachment):
150150
"""

asabiris/orchestration/sendslack.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import logging
22
import fastjsonschema
33

4+
from .. exceptions import PathError
45
from ..schemas import slack_schema
56

67
L = logging.getLogger(__name__)
@@ -35,8 +36,8 @@ async def send_to_slack(self, msg):
3536
# - if it is not absolute path, it is file name - assume it's a file in Templates folder
3637

3738
# templates must be stores in /Templates/Slack
38-
if not body['template'].startswith("/Templates/Slack"):
39-
raise ValueError("Template must be stored in /Templates/Slack directory")
39+
if not body['template'].startswith("/Templates/Slack/"):
40+
raise PathError(path=body['template'])
4041

4142
body["params"] = body.get("params", {})
4243
output = await self.JinjaService.format(body["template"], body["params"])

qa.md

+15-15
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@
8585

8686

8787

88-
## TSM005: Try to send an email with template as body and attachment.
88+
## TSM005: Try to send an email with template as body and attachment.(Format=pdf)
8989

9090
`PUT /send_mail`
9191

@@ -112,7 +112,7 @@
112112
```
113113

114114

115-
## TSM005: Try to send an email with template as body and attachment.
115+
## TSM006: Try to send an email with template as body and attachment.(Format=html)
116116

117117
`PUT /send_mail`
118118

@@ -138,7 +138,7 @@
138138
}
139139
```
140140

141-
## TSM006: Try to send an email with template as body and a missing html attachment.
141+
## TSM007: Try to send an email with template as body and a missing html attachment.
142142

143143
`PUT /send_mail`
144144

@@ -165,7 +165,7 @@
165165
166166
```
167167

168-
## TSM007: Try to send an email with template as body and a missing html attachment.
168+
## TSM008: Try to send an email with template as body and a missing html attachment.
169169

170170

171171
`PUT /send_mail`
@@ -193,7 +193,7 @@
193193
```
194194

195195

196-
## TSM008: Try to send an email with missing template
196+
## TSM009: Try to send an email with missing template
197197

198198
`PUT /send_mail`
199199

@@ -207,7 +207,7 @@
207207
208208
```
209209

210-
## TSM009: Try to send an email with no template
210+
## TSM0010: Try to send an email with no template
211211

212212
`PUT /send_mail`
213213

@@ -226,7 +226,7 @@ EXPECTED RESPONSE:
226226
}
227227
```
228228

229-
## TSM010: Try to send an email with base64 attachment.
229+
## TSM011: Try to send an email with base64 attachment.
230230

231231
`PUT /send_mail`
232232

@@ -244,7 +244,7 @@ EXPECTED RESPONSE:
244244
}
245245
```
246246

247-
## TSM011: Try to render PDF report using html template
247+
## TSM012: Try to render PDF report using html template
248248

249249
`PUT /render?format=html&template=/Templates/General/hello.html`
250250

@@ -254,7 +254,7 @@ EXPECTED RESPONSE:
254254
}
255255
```
256256

257-
## TSM012: Try to render PDF report using html template
257+
## TSM013: Try to render PDF report using html template
258258

259259
`PUT /render?format=pdf&template=/Templates/General/hello.html`
260260

@@ -264,7 +264,7 @@ EXPECTED RESPONSE:
264264
}
265265
```
266266

267-
## TSM013: Try to render PDF report using markdown template
267+
## TSM014: Try to render PDF report using markdown template
268268

269269
`PUT /render?format=pdf&template=/Templates/General/hello.md`
270270

@@ -274,7 +274,7 @@ EXPECTED RESPONSE:
274274
}
275275
```
276276

277-
## TSM014: Try to render PDF report using html template
277+
## TSM015: Try to render PDF report using html template
278278

279279
`PUT /render?format=html&template=/Templates/General/hello.md`
280280

@@ -284,7 +284,7 @@ EXPECTED RESPONSE:
284284
}
285285
```
286286

287-
## TSM015: Try to render PDF using missing template
287+
## TSM016: Try to render PDF using missing template
288288

289289
`PUT /render?format=pdf&template=/Templates/MISSING.html`
290290

@@ -300,7 +300,7 @@ EXPECTED RESPONSE:
300300
}
301301
```
302302

303-
## TSM016: Try to render HTML using missing template
303+
## TSM017: Try to render HTML using missing template
304304

305305
`PUT /render?format=html&template=/Templates/MISSING.html`
306306

@@ -317,7 +317,7 @@ EXPECTED RESPONSE:
317317
}
318318
```
319319

320-
## TSM017: Try to send Slack message using markdown template
320+
## TSM018: Try to send Slack message using markdown template
321321

322322
`PUT /send_slack`
323323

@@ -333,7 +333,7 @@ EXPECTED RESPONSE:
333333
}
334334
```
335335

336-
## TSM018: Try to send Slack message using missing template
336+
## TSM019: Try to send Slack message using missing template
337337

338338
`PUT /send_slack`
339339

0 commit comments

Comments
 (0)