Created
December 18, 2013 06:21
-
-
Save XuefengWu/8018058 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.util.{Failure, Success, Try} | |
import play.api.libs.json.{Json, JsValue} | |
import play.api.LoggerLike | |
trait BusinessProcess extends PropertiesContext { | |
def logger: LoggerLike | |
def processRequest[A, B](bodyExtractor: => A, doBusiness: A => BusinessResult[B]): BusinessResult[B] = { | |
Try(bodyExtractor) match { | |
case Success(t) => doBusiness(t) | |
case Failure(e) => { | |
logger.warn(s"fail when parse request.body", e) | |
FailedResult(invalidJson, message("invalid.json.format")) | |
} | |
} | |
} | |
def checkThenAct[A](validations: (Boolean, FailedResult)*)(action: => BusinessResult[A]): BusinessResult[A] = { | |
val failedResults = | |
for ((failed, failedResult) <- validations if failed) | |
yield failedResult | |
failedResults.foreach(fail => logger.warn(s"errorCode=[${fail.errorCode.toString}], messages=${fail.messages}")) | |
failedResults.headOption.getOrElse(action) | |
} | |
def generateErrorMessage(errorCode: ErrorCode, msgs: String*): JsValue = generateErrorMessage(None, errorCode, msgs: _*) | |
def generateErrorMessage(input: Option[String], errorCode: ErrorCode, msgs: String*): JsValue = { | |
val msgArray = msgs.map(Utils.escapeForJson).mkString( """ ["""", """","""", """"] """) | |
val raw = s""" {"errorCode": "$errorCode", "messages": $msgArray } """ | |
logger.warn(raw) | |
input.foreach(m => logger.warn(s"input:\n $m")) | |
Json.parse(raw) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment