本文整理汇总了Scala中org.postgresql.util.PSQLException类的典型用法代码示例。如果您正苦于以下问题:Scala PSQLException类的具体用法?Scala PSQLException怎么用?Scala PSQLException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PSQLException类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: UserRoute
//设置package包名称以及导入依赖的类
package se.meldrum.machine.http.routes
import akka.http.scaladsl.server.Directives._
import org.postgresql.util.PSQLException
import se.meldrum.machine.dao.UserDao
import se.meldrum.machine.db.models.User
import se.meldrum.machine.http.UserCreation
import slick.driver.PostgresDriver.api._
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
class UserRoute(implicit db: Database, implicit val ec: ExecutionContext) {
private val dao = new UserDao()
import se.meldrum.machine.http.JsonSupport._
val route =
pathPrefix("user") {
get {
complete(dao.getUserNames())
}~
path("create") {
post {
entity(as[UserCreation]) { user=>
import com.github.t3hnar.bcrypt._
val cryptedPass = user.password.bcrypt
val u = User(None, user.name, cryptedPass, user.email)
complete(createUser(u))
}
}
}~
path("delete") {
post {
entity(as[String]) { username =>
complete(deleteUser(username))
}
}
}
}
private def createUser(u: User): Future[String] = {
val result = dao.create(u).map {
case Success(u) => "User created"
case Failure(e: PSQLException) if e.getSQLState == "23505" => "User already exists"
case Failure(e) => e.getMessage
}
result
}
private def deleteUser(user: String): Future[String] = {
val result = dao.delete(user).map {
case Success(v) => "returned " + v
case Failure(e) => e.getMessage
}
result
}
}
开发者ID:Max-Meldrum,项目名称:machine,代码行数:61,代码来源:UserRoute.scala
示例2: Handler
//设置package包名称以及导入依赖的类
package org.birdfeed.chirp.errors
import com.google.inject.Singleton
import org.postgresql.util.PSQLException
import play.api.http.HttpErrorHandler
import play.api.mvc.Results._
import play.api.mvc._
import scala.concurrent._
@Singleton
class Handler extends HttpErrorHandler with JsonError {
def onClientError(request: RequestHeader, statusCode: Int, message: String) = {
Future.successful(
Status(statusCode)("A client error occurred: " + message)
)
}
def onServerError(request: RequestHeader, exception: Throwable) = {
Future.successful(exception match {
case ex: PSQLException => {
BadRequest(jsonException("A database error has occurred.", ex))
}
// TODO: Fix this
// case ex: AuthenticationFailedException => {
// Unauthorized(jsonException("Invalid credentials.", ex))
// }
case ex: Exception => {
InternalServerError(jsonException("An ISE has occurred.", ex))
}})
}
}
开发者ID:AwesomeIT,项目名称:chirp,代码行数:34,代码来源:Handler.scala
示例3: Validations
//设置package包名称以及导入依赖的类
package com.wunder.pets.validations
import cats.data
import cats.data.{NonEmptyList, ValidatedNel}
import eu.timepit.refined.api.Validate
import eu.timepit.refined.refineV
import org.postgresql.util.PSQLException
object Validations {
type Validated[T] = ValidatedNel[ValidationError, T]
type Errors = NonEmptyList[ValidationError]
type ErrorMessages = Seq[String]
type WithErrorMessages[T] = Either[ErrorMessages, T]
def validate[VALUE, VALIDATION](v: VALUE, e: ValidationError)
(implicit validation: Validate[VALUE, VALIDATION]): Validated[VALUE] = {
val validated: Either[Errors, VALUE] = refineV[VALIDATION](v)
.left.map(_ => NonEmptyList(e, Nil))
.right.map(_.value)
data.Validated.fromEither(validated)
}
def assureUnique[T]: PartialFunction[Throwable, WithErrorMessages[T]] = {
case e: PSQLException => {
toErrorMessages(dbError(e))
}
}
def dbError(e: PSQLException): Errors = {
def isUniquenessViolation(e: PSQLException) = e.getServerErrorMessage.getDetail.matches(".* already exists.")
val error = if (isUniquenessViolation(e)) {
new DuplicateValue(e)
} else {
new GeneralError(e.getMessage)
}
NonEmptyList(error, Nil)
}
def toErrorMessages[T](errors: Errors): WithErrorMessages[T] = Left(errors.map(_.message).toList)
}
开发者ID:wunderteam,项目名称:battle-pets-api,代码行数:42,代码来源:Validations.scala
示例4: message
//设置package包名称以及导入依赖的类
package com.wunder.pets.validations
import java.util.regex.{Matcher, Pattern}
import org.postgresql.util.PSQLException
trait ValidationError {
def message: String
}
final class IsEmpty(val field: String) extends ValidationError {
override def message: String = s"$field cannot be empty"
}
final class NotGreaterThan[T](val field: String, val lowerBound: T) extends ValidationError {
def message: String = s"$field must be greater than $lowerBound"
}
final class NotLessThan[T](val field: String, val upperBound: T) extends ValidationError {
def message: String = s"$field must be less than $upperBound"
}
final class DuplicateValue(val e: PSQLException) extends ValidationError {
override def message: String = {
val regex = "Key \\((.*)\\)=\\((.*)\\) already exists."
val m: Matcher = Pattern.compile(regex).matcher(e.getServerErrorMessage.getDetail);
if (m.matches) {
s"${m.group(1)} has a duplicate value of ${m.group(2)}"
} else {
"Could not determine field and value."
}
}
}
final class GeneralError(val message: String) extends ValidationError
开发者ID:wunderteam,项目名称:battle-pets-api,代码行数:36,代码来源:ValidationError.scala
示例5: DuplicateValueSpec
//设置package包名称以及导入依赖的类
package validations
import com.wunder.pets.validations.DuplicateValue
import org.postgresql.util.{PSQLException, ServerErrorMessage}
import org.scalatest.{MustMatchers, WordSpec}
class DuplicateValueSpec extends WordSpec with MustMatchers {
"message" should {
"extract field and value" in {
val errorMessage = "SERROR\u0000VERROR\u0000C23505\u0000Mduplicate key value violates unique constraint \"name_unique_idx\"\u0000DKey (someField)=(Foo) already exists.\u0000spublic\u0000tpets\u0000nname_unique_idx\u0000Fnbtinsert.c\u0000L433\u0000R_bt_check_unique\u0000\u0000"
val serverError = new ServerErrorMessage(errorMessage, 0)
val originalError = new PSQLException(serverError)
val result = new DuplicateValue(originalError).message
result.mustEqual("someField has a duplicate value of Foo")
}
}
}
开发者ID:wunderteam,项目名称:battle-pets-api,代码行数:22,代码来源:DuplicateValueSpec.scala
示例6: ValidationsSpec
//设置package包名称以及导入依赖的类
package validations
import com.wunder.pets.validations.Validations
import org.postgresql.util.{PSQLException, ServerErrorMessage}
import org.scalatest.{MustMatchers, WordSpec}
class ValidationsSpec extends WordSpec with MustMatchers {
"dbError" when {
"given a uniqueness constraint error" should {
"parse to a uniqueness error" in {
val errorMessage = "SERROR\u0000VERROR\u0000C23505\u0000Mduplicate key value violates unique constraint \"name_unique_idx\"\u0000DKey (name)=(Bob) already exists.\u0000spublic\u0000tpets\u0000nname_unique_idx\u0000Fnbtinsert.c\u0000L433\u0000R_bt_check_unique\u0000\u0000"
val serverError = new ServerErrorMessage(errorMessage, 0)
val originalError = new PSQLException(serverError)
val result = Validations.dbError(originalError)
val validationError = result.head
validationError.message.mustEqual("name has a duplicate value of Bob")
}
}
}
}
开发者ID:wunderteam,项目名称:battle-pets-api,代码行数:23,代码来源:ValidationsSpec.scala
示例7: SilentDbImporter
//设置package包名称以及导入依赖的类
package com.snapswap.db.helpers.runner
import java.sql.BatchUpdateException
import com.snapswap.db.errors.{DataError, EntityNotFound, InternalDataError, OverrideNotAllowed}
import org.postgresql.util.PSQLException
import slick.basic.BasicBackend
import slick.dbio.{DBIOAction, NoStream}
import slick.util.TreePrinter
import scala.annotation.tailrec
import scala.concurrent.{ExecutionContext, Future}
trait DbRunSafe {
private[this] val pSQLExceptionErrCodes = Set("23505", "23503")
implicit class SilentDbImporter[D <: BasicBackend#DatabaseDef](db: D) {
def runSafe[R](a: DBIOAction[R, NoStream, Nothing])(implicit ec: ExecutionContext): Future[R] = {
def additionalInfo = TreePrinter.default.get(a)
db.run(a).recoverWith {
case ex: UnsupportedOperationException if ex.getMessage == "empty.head" => // When query returns no results then UnsupportedOperationException("empty.head") is thrown instead of NoSuchElementException
Future.failed[R](EntityNotFound(dbDetails = Some(additionalInfo)))
case _: NoSuchElementException =>
Future.failed[R](EntityNotFound(dbDetails = Some(additionalInfo)))
case ex: PSQLException =>
// wrap with Option to avoid NullPointerException
Option(ex.getServerErrorMessage).flatMap(msg => Option(msg.getSQLState)) match {
case Some(sqlState) if pSQLExceptionErrCodes.contains(sqlState) =>
Future.failed[R](OverrideNotAllowed(dbDetails = Some(additionalInfo)))
case _ =>
Future.failed[R](InternalDataError(ex.getMessage, dbDetails = Some(additionalInfo)))
}
case ex: DataError =>
Future.failed[R](ex)
case ex: BatchUpdateException =>
Future.failed[R](InternalDataError(ex.getMessage, dbDetails = Some(getAllExceptions(ex))))
case ex =>
Future.failed[R](InternalDataError(ex.getMessage, dbDetails = Some(additionalInfo)))
}
}
}
@tailrec
private[this] def getAllExceptions(exception: BatchUpdateException, msg: List[String] = List.empty): String = exception match {
case ex: BatchUpdateException =>
ex.getNextException match {
case next: BatchUpdateException =>
getAllExceptions(ex, s"${next.getClass.getSimpleName}: ${next.getMessage}" :: msg)
case ex: PSQLException =>
(s"${ex.getClass.getSimpleName}: ${ex.getMessage}" :: msg).reverse.mkString(",")
}
case _ =>
msg.reverse.mkString(",")
}
}
object DbRunHelper extends DbRunSafe
开发者ID:snap-swap,项目名称:slick-postgres-helpers,代码行数:60,代码来源:DbRunHelper.scala
示例8: db
//设置package包名称以及导入依赖的类
package org.dohrm.toolkit.utils
import com.github.tototoshi.slick.{PostgresJodaSupport, GenericJodaSupport}
import org.dohrm.toolkit.actor.response.{InvalidRequestError, ExceptionError, Error}
import org.dohrm.toolkit.context.{ConfigContext, JdbcConfig, JdbcContext}
import org.postgresql.util.PSQLException
import slick.driver.JdbcProfile
import slick.jdbc.JdbcBackend
trait PostgresSupport extends JdbcContext {
self: ConfigContext =>
private val DbConfig = config.getConfig("postgres")
private lazy val lazyDb = JdbcBackend.Database.forURL(
url = s"jdbc:postgresql://${DbConfig.getString("url")}:${DbConfig.getString("port")}/${DbConfig.getString("database")}",
user = DbConfig.getString("user"),
password = DbConfig.getString("password"),
driver = DbConfig.getString("driver"),
keepAliveConnection = DbConfig.getBoolean("keepAliveConnection")
)
override implicit lazy val jdbcConfig: JdbcConfig = new JdbcConfig {
override val jodaSupport: GenericJodaSupport = PostgresJodaSupport
override def db: JdbcBackend.DatabaseDef = lazyDb
override val driver: JdbcProfile = slick.driver.PostgresDriver
override def exceptionToErrorMapper: PartialFunction[Throwable, Error] = {
case e: PSQLException if e.getServerErrorMessage.getSQLState == "23505"=>
InvalidRequestError(Seq(s"${e.getServerErrorMessage.getTable.toLowerCase}.unique_violation"))
case e: PSQLException =>
println(e.getServerErrorMessage)
ExceptionError(e)
}
}
}
开发者ID:dohr-michael,项目名称:storyline,代码行数:42,代码来源:PostgresSupport.scala
示例9: PSQLExceptionMapper
//设置package包名称以及导入依赖的类
package io.github.vjames19.finatraexample.blog.api.exceptions
import javax.inject.Inject
import com.twitter.finagle.http.{Request, Response}
import com.twitter.finatra.http.exceptions.ExceptionMapper
import com.twitter.finatra.http.response.ResponseBuilder
import com.twitter.inject.Logging
import org.postgresql.util.PSQLException
class PSQLExceptionMapper @Inject()(response: ResponseBuilder) extends ExceptionMapper[PSQLException] with Logging {
// Error Codes: https://www.postgresql.org/docs/9.6/static/errcodes-appendix.html
val integrityConstraintViolation: String = "23"
override def toResponse(request: Request, throwable: PSQLException): Response = {
val code = throwable.getServerErrorMessage.getSQLState
if (code.startsWith(integrityConstraintViolation)) {
response.badRequest(throwable.getServerErrorMessage.toString)
} else {
error("Something went wrong", throwable)
response.internalServerError("Something went wrong")
}
}
}
开发者ID:vjames19,项目名称:finatra-example,代码行数:28,代码来源:PSQLExceptionMapper.scala
示例10: PermissionServiceImpl
//设置package包名称以及导入依赖的类
package auth.direct.service.impl
import java.util.UUID
import auth.core.model.core.{Permission, PermissionToUser}
import auth.direct.persistence.model.{AuthDatabaseConfigProvider, AuthDbAccess, CoreAuthTablesDefinitions}
import auth.direct.service.PermissionService
import org.postgresql.util.PSQLException
import scala.concurrent.{ExecutionContext, Future}
class PermissionServiceImpl(protected val dbConfigProvider: AuthDatabaseConfigProvider)(
implicit ec: ExecutionContext)
extends PermissionService with AuthDbAccess with CoreAuthTablesDefinitions {
import driver.api._
val api = new Api()(ec)
override def grant(permission: Permission, userUuid: UUID): Future[Boolean] =
db.run(api.Permissions.grant(permission, userUuid)).recoverWith {
case e: PSQLException ? Future.successful(false)
}
override def revoke(permission: Permission, userUuid: UUID): Future[Boolean] =
db.run(api.Permissions.revoke(permission, userUuid))
override def allPossible(): Future[Seq[Permission]] =
db.run(permissionsQuery.result)
override def find(permission: Permission, userUuid: UUID): Future[Option[PermissionToUser]] =
db.run(api.Permissions.find(permission, userUuid))
override def allAssigned(): Future[Seq[PermissionToUser]] =
db.run(permissionsToUsersQuery.result)
override def allOfUser(userUuid: UUID): Future[Seq[PermissionToUser]] =
db.run(api.PermissionsToUsers.allOfUser(userUuid))
}
开发者ID:KadekM,项目名称:play-slick-silhouette-auth-api,代码行数:39,代码来源:PermissionServiceImpl.scala
注:本文中的org.postgresql.util.PSQLException类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论