From 6063ccef3a205b01dbb063b355f0a41c79a35581 Mon Sep 17 00:00:00 2001 From: eikek Date: Sat, 4 Jun 2022 19:08:29 +0200 Subject: [PATCH] Return 400 when input is invalid instead of server error --- .../routes/NotificationRoutes.scala | 26 ++++++++++++++----- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/modules/restserver/src/main/scala/docspell/restserver/routes/NotificationRoutes.scala b/modules/restserver/src/main/scala/docspell/restserver/routes/NotificationRoutes.scala index fd244fc2cb..e0c9f0bde9 100644 --- a/modules/restserver/src/main/scala/docspell/restserver/routes/NotificationRoutes.scala +++ b/modules/restserver/src/main/scala/docspell/restserver/routes/NotificationRoutes.scala @@ -6,7 +6,7 @@ package docspell.restserver.routes -import cats.data.NonEmptyList +import cats.data.{EitherT, NonEmptyList} import cats.effect._ import cats.implicits._ @@ -64,17 +64,29 @@ object NotificationRoutes extends NonEmptyListSupport { case req @ POST -> Root => for { input <- req.as[NotificationChannel] - ch <- Sync[F].pure(NotificationChannel.convert(input)).rethrow - res <- backend.notification.createChannel(ch, user.account) - resp <- Ok(Conversions.basicResult(res, "Channel created")) + ch <- Sync[F].pure(NotificationChannel.convert(input)) + resp <- EitherT + .fromEither[F](ch) + .semiflatMap { c => + backend.notification + .createChannel(c, user.account) + .map(res => Conversions.basicResult(res, "Channel created")) + } + .foldF(ex => BadRequest(BasicResult(false, ex.getMessage)), Ok(_)) } yield resp case req @ PUT -> Root => for { input <- req.as[NotificationChannel] - ch <- Sync[F].pure(NotificationChannel.convert(input)).rethrow - res <- backend.notification.updateChannel(ch, user.account) - resp <- Ok(Conversions.basicResult(res, "Channel created")) + ch <- Sync[F].pure(NotificationChannel.convert(input)) + resp <- EitherT + .fromEither[F](ch) + .semiflatMap { c => + backend.notification + .updateChannel(c, user.account) + .map(res => Conversions.basicResult(res, "Channel created")) + } + .foldF(ex => BadRequest(BasicResult(false, ex.getMessage)), Ok(_)) } yield resp } }