抛出新的异常并没有显示帖子中的任何回复

时间:2017-11-12 11:41:28

标签: scala exception playframework

我正在开发一个播放scala应用程序,我发现异常一旦找不到语言环境抛出过滤器,我的问题是邮件一旦发生异常就不会显示在邮递员中我不明白为什么,这里是我的代码

class LocaleFilter @Inject()(implicit val mat: Materializer, ec: ExecutionContext) extends Filter {

  def apply(nextFilter: RequestHeader => Future[Result])
           (requestHeader: RequestHeader): Future[Result] = {

    val startTime = System.currentTimeMillis
    val localeIndex = requestHeader.path.indexOf("v1") + 3
    val localeRequest = requestHeader.path.replace("//", "/").split("/")(3);
    if (!isExistingLocale(localeRequest)) {
      throw new CustomException("Locale not found")
    }
    nextFilter(requestHeader).map { result =>

      val endTime = System.currentTimeMillis
      val requestTime = endTime - startTime

      Logger.info(s"${requestHeader.method} ${requestHeader.uri} took ${requestTime}ms and returned ${result.header.status}")

      result.withHeaders("Request-Time" -> requestTime.toString)
    }


  }

  def isExistingLocale(locale: String): Boolean = {

    val properties = ConnectionLoader.getConnectionProperties(locale);
    return null != properties;

  }

  case class CustomException(private val message: String = "",
                             private val cause: Throwable = None.orNull)
    extends Exception(message, cause)

}

这是邮递员结果enter image description here

帖子man结果应该是找不到的错过而且代码是500的语言环境

1 个答案:

答案 0 :(得分:1)

要解决您的问题,您可以使用trait Results(我不知道它是否是最佳解决方案)。这是过滤器的例子:

import akka.stream.Materializer
import javax.inject._
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}

@Singleton
class ExampleFilter @Inject()(
    implicit override val mat: Materializer,
    exec: ExecutionContext) extends Filter with Results { // added `with Results` to be able to use `InternalServerError`

  override def apply(nextFilter: RequestHeader => Future[Result])
           (requestHeader: RequestHeader): Future[Result] = {
    // ...

    if(/* ... */){
        return Future.successful(InternalServerError("Locale not found"))
    }

    // ...

    nextFilter(requestHeader).map { result =>
       // ...
    }
  }

}

卷曲返回500,并带有正确的消息:

$ curl -v http://localhost:9000
* Rebuilt URL to: http://localhost:9000/
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 9000 (#0)
> GET / HTTP/1.1
> Host: localhost:9000
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 500 Internal Server Error
< Content-Length: 16
< Content-Type: text/plain; charset=utf-8
< Date: Sun, 12 Nov 2017 13:31:43 GMT
< 
* Connection #0 to host localhost left intact
Locale not found%