当发生错误时,Cloudopt Next将会自动调用错误拦截器进行处理。默认的错误拦截器 DefaultErrorHandler 会拦截 404 和 500 错误并输出错误信息。
如果您需要处理更多错误,可以模仿 DefaultErrorHandler 创建一个Handler,并在配置文件中修改相应的配置即可。
class DefaultErrorHandler : ErrorHandler() {
override fun handle(statusCode: Int, throwable: Throwable?) {
if (abs(errorStatusCode) == 404) {
response.putHeader(HttpHeaders.CONTENT_TYPE, "text/html;charset=utf-8")
context.response().end(Welcomer.notFound())
return
}
if (abs(errorStatusCode) == 500) {
response.putHeader(HttpHeaders.CONTENT_TYPE, "text/html;charset=utf-8")
context.response().end(Welcomer.systemError())
return
}
val errorMessage = if ((throwable?.message ?: "").isNotBlank()) {
throwable?.message ?: ""
} else if (context.data().containsKey("errorMessage")) {
context.data()["errorMessage"].toString()
} else {
"This is a bad http request, please check if the parameters match the requirements."
}
renderJson(creatResult(errorStatusCode.toString(), errorMessage))
}
private fun creatResult(error: String, errorMessage: String): HashMap<String, String> {
val map = hashMapOf<String, String>()
map["error"] = error
map["errorMessage"] = errorMessage
return map
}
private val errorStatusCode: Int
get() {
if (this.context.statusCode() > 0) {
this.response.statusCode = this.context.statusCode()
} else {
this.response.statusCode = 500
}
return this.response.statusCode
}
}