服务器错误消息的正确正则表达式

Proper regular expression for server error message

本文关键字:正则表达式 错误 消息 服务器      更新时间:2023-12-29

我正在进行Ajax调用,并且从服务器收到一个错误。

现在的问题是我收到了以下消息。

HTTP Status 756 - Error while processing the request.
--------------------------------------------------------------------------------
type Status report
message Error while processing the request.
description Cannot find message associated with key http.756

我只想从完整的错误报告中得到错误消息,而不是上面的所有文本。我该怎么做?

但实际的反应是

<html><head><title>Apache Tomcat/5.0.28 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 756 - Error while processing the request.</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>Error while processing the request.</u></p><p><b>description</b> <u>Cannot find message associam<D‡üñÔE(1@@ähttp.756</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/5.0.28</h3></body></html>​

从我想获得错误消息的位置。

当您取回response HTML时,您可以像这样获取消息…

var div = document.createElement("div");
div.innerHTML = response;
var errorMsg = [].filter.call(div.getElementsByTagName("b"), function(b) {
    return b.textContent == "message";
})[0].nextElementSibling.textContent || "Unknown error";

jsFiddle。


如果只是短信。。。

这将提取第一行-之后的文本。如果找不到匹配项,它将返回"未知错误"。

var errorMsg = (response.split("'n")[0].match(/^HTTP Status 'd+ - (.+)$/) 
                || [])[1]
                || "Unknown error";

jsFiddle。

如果您希望匹配下面的message行。

var errorMsg = (response.match(/^message (.+)$/m) || [])[1] || "Unknown error";

jsFiddle。

检查这个工作示例:Regex

(?<=-'s).*

(?<=[0-9]'s-'s).*

这将获取准确的台面:Error while processing the request.

编辑

如果它包含HTML,那么这将起作用:更新Regex

(?<=<h1>).*(?=</h1>)

我通过以下JavaScript代码得到了答案。

var res = "Error Message : '";
var bonly = data.responseText.match(/<h1>(.*?)<'/h1>/);
if (bonly && (bonly.length > 1)) {
    res += bonly[1];
}
res += "'. Error Code : ";
res += data.status;
return res;