1
1
package com.example.plugins
2
2
3
+ import com.example.exceptions.DbElementInsertException
3
4
import com.example.exceptions.DbElementNotFoundException
4
5
import com.example.models.Article
5
6
import com.example.service.ArticleService
@@ -17,38 +18,44 @@ fun Application.configureRouting(dbConnection: Connection) {
17
18
// Create new Article
18
19
post(" /articles" ) {
19
20
val article = call.receive<Article >()
20
- val id = articleService.create(article)
21
- call.respond(HttpStatusCode .Created , id)
21
+ try {
22
+ val id = articleService.create(article)
23
+ call.respond(HttpStatusCode .Created , id)
24
+ } catch (cause: DbElementInsertException ) {
25
+ call.respond(HttpStatusCode .InternalServerError )
26
+ }
22
27
}
23
28
// Read an Article
24
29
get(" /articles/{id}" ) {
25
- val id = call.parameters[" id" ]?.toInt() ? : throw DbElementNotFoundException (" Invalid article ID" )
26
30
try {
31
+ val id = call.parameters[" id" ]?.toInt() ? : throw IllegalArgumentException (" Invalid article ID" )
27
32
val article = articleService.read(id)
28
33
call.respond(HttpStatusCode .OK , article)
29
34
} catch (cause: DbElementNotFoundException ) {
30
35
call.respond(HttpStatusCode .NotFound )
36
+ } catch (cause: IllegalArgumentException ) {
37
+ call.respond(HttpStatusCode .BadRequest )
31
38
}
32
39
}
33
40
// Update an Article
34
41
put(" /articles/{id}" ) {
35
- val id = call.parameters[" id" ]?.toInt() ? : throw DbElementNotFoundException (" Invalid article ID" )
36
42
try {
43
+ val id = call.parameters[" id" ]?.toInt() ? : throw IllegalArgumentException (" Invalid article ID" )
37
44
val article = call.receive<Article >()
38
45
articleService.update(id, article)
39
46
call.respond(HttpStatusCode .OK )
40
- } catch (cause: DbElementNotFoundException ) {
41
- call.respond(HttpStatusCode .NotFound )
47
+ } catch (cause: IllegalArgumentException ) {
48
+ call.respond(HttpStatusCode .BadRequest )
42
49
}
43
50
}
44
51
// Delete an Article
45
52
delete(" /articles/{id}" ) {
46
- val id = call.parameters[" id" ]?.toInt() ? : throw DbElementNotFoundException (" Invalid article ID" )
47
53
try {
54
+ val id = call.parameters[" id" ]?.toInt() ? : throw IllegalArgumentException (" Invalid article ID" )
48
55
articleService.delete(id)
49
56
call.respond(HttpStatusCode .OK )
50
- } catch (cause: DbElementNotFoundException ) {
51
- call.respond(HttpStatusCode .NotFound )
57
+ } catch (cause: IllegalArgumentException ) {
58
+ call.respond(HttpStatusCode .BadRequest )
52
59
}
53
60
}
54
61
}
0 commit comments