这是我不断增长validationRejectionHandler
的喷雾项目:
implicit def validationRejectionHandler = RejectionHandler {
case ValidationRejection(errMsg,_) :: _ =>
logger.info(s"received validation error: $errMsg")
complete(StatusCodes.Unauthorized,errMsg)
case MalformedQueryParamRejection(parameterName, errorMsg, cause) :: _ =>
logger.debug(s"received MalformedQueryParamRejection error: $errorMsg")
complete(BadRequest -> GenericMessageObj(s"The query parameter $parameterName was malformed: $errorMsg"))
case spray.routing.AuthorizationFailedRejection :: _ =>
//todo - this string shouldn't be here
logger.info("received authentication error")
complete(StatusCodes.Unauthorized, "User is not authorized to this resource")
case MalformedRequestContentRejection(msg, causeOpt) :: _ =>
complete {
causeOpt.map { cause =>
cause match {
case e: InvalidFormatException =>
val fieldNameMatcher = """\["(.+)"\]""".r.unanchored
val fieldTypeMatcher = """(\w+)$""".r.unanchored
e.getPath.toString match {
case fieldNameMatcher(fieldName) =>
e.getTargetType.toString match {
case fieldTypeMatcher(fieldType) =>
val fieldTypeLowerCase = fieldType.toLowerCase()
BadRequest -> GenericMessageObj(s"""Invalid data: "${fieldName}" must be a ${fieldTypeLowerCase} value, but received ${e.getValue}""")
case _ =>
BadRequest -> GenericMessageObj(s"""${e.getValue} is an improper type for field "${fieldName}""")
}
case _ =>
logger.debug(s"Failed pattern match: ${e.getPath.toString}")
BadRequest -> GenericMessageObj("Invalid payload format")
}
case e: UnrecognizedPropertyException => BadRequest -> GenericMessageObj(s"Unrecognized property: ${e.getPropertyName}")
case e: JsonMappingException =>
if(cause.getCause == null || cause.getCause.getMessage == null){
val deserializationMsgMatcher = """Can not deserialize instance of scala\.collection\.(Seq) out of (VALUE_NUMBER_INT) [\s\S]+"(name)":[+-]?\d\};[\s\S]+\["(\3)"\].+""".r.unanchored
cause.getMessage match {
case deserializationMsgMatcher(expected, actual, fieldName, _) =>
logger.debug(s"Desrializaiton error at $fieldName: Found $actual instead of $expected")
BadRequest -> GenericMessageObj(s"Invalid format for $fieldName")
case _ =>
BadRequest -> GenericMessageObj(s"${cause.getMessage}")
}
} else if (!cause.getCause.getMessage.isEmpty) {
BadRequest -> GenericMessageObj(cause.getCause.getMessage)
} else {
BadRequest -> GenericMessageObj(s"Invalid data format")
}
case _ => BadRequest -> GenericMessageObj(s"An unknown error occurred.")
}
}
}
case spray.routing.MissingHeaderRejection(headerName) :: _ =>
complete(BadRequest -> GenericMessageObj("%s header is missing.".format(headerName)))
}
}
在我看来,这段令人费解的代码——用正则表达式来破译各种类型的错误——是在 Spray 中处理拒绝的方法,这样它就不会向 API 客户端吐回这样的丑陋消息,这对我来说似乎很疯狂:
{ "message": "在 [Source: {\n \"source\": \"k\",\n \"values\": [\n { \n \"dt\": \"2015-10-15T16:27:42.014Z\",\n \"id\":\"0022A3000004E6E1\",\n \n \"属性\":\"a \",\n \"_id\": \"45809haoua\",\n \"__id\": \"a2p49t7ya4wop9h\",\n \"___id\": \"q2ph84yhtq4pthqg\"\n }]\n }; line: 12, column: 9] (通过引用链:io.keenhome.device.models.DatumList[\"values\"]->com.fasterxml.jackson.module.scala.deser.BuilderWrapper[0]) " }
如何处理这些错误消息(例如向 API 客户端返回非垃圾),而不必对可能更改的字符串执行正则表达式?