Skip to content
Snippets Groups Projects
Commit 9724bef7 authored by Felipe D'Abrantes's avatar Felipe D'Abrantes
Browse files

Add better exception handling for unknown Dailies

parent 9040190d
No related branches found
No related tags found
1 merge request!14Add endpoints to manage Dailies
......@@ -5,7 +5,7 @@ import play.api.mvc._
import play.api.libs.json.JsValue
import models.{Daily}
import models.exceptions.ConflictException
import models.exceptions.{ConflictException, NotFoundException}
import scala.concurrent.TimeoutException
import org.bson.types.ObjectId
......@@ -94,6 +94,7 @@ class DailyController @Inject()(val controllerComponents: ControllerComponents)
} catch {
case _: TimeoutException => BadRequest("Request timed out")
case ex: ConflictException => BadRequest(ex.getMessage())
case ex: NotFoundException => BadRequest(ex.getMessage())
case _: Throwable => BadRequest("Exception raised")
}
}
......
package models
import repositories.{DailyRepository}
import models.exceptions.{ConflictException}
import models.exceptions.{ConflictException, NotFoundException}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Future, Await}
......@@ -66,8 +66,11 @@ object Daily {
def likeAsync(dailyId: ObjectId, likerId: ObjectId, timeout: Int = 4): Unit = {
val result: Future[Unit] = for {
daily: Daily <- dailyRepo.getById(dailyId)
oDaily: Option[Daily] <- dailyRepo.getById(dailyId)
like: Unit <- {
// Check daily with given ID exists
val daily = if (oDaily.isEmpty) throw new NotFoundException("No daily with given ID.") else oDaily.get
// Check user has not already liked Daily
if (daily.usersLiked.contains(likerId)) throw new ConflictException("User has already liked this Daily.")
......
package models.exceptions
case class NotFoundException(message: String) extends Exception(message)
......@@ -55,11 +55,11 @@ class Repository[T: ClassTag](databaseName: String, collectionName: String) {
/**
* Gets a record with the given ID in the collection.
*
* @return A Future containing a sequence of matching documents.
* @return A Future containing an optional matching document.
*/
def getById(id: ObjectId): Future[T] = {
def getById(id: ObjectId): Future[Option[T]] = {
val filter: Bson = Filters.equal[ObjectId]("_id", id)
MongoConnection.find[T](collection, filter).map(_.head)
MongoConnection.find[T](collection, filter).map(_.headOption)
}
/**
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment