Gre*_*ner 0 delphi exception-handling http indy
我的问题涉及我从URL中加载图像的另一个问题.以下代码有效.但是,如果我试图获取图像(它假设在那里)我遇到了问题,但显然已被删除.应用程序不知道并返回错误.有没有办法通过捕获传入的错误来防止它.我将不胜感激任何建议.它发生在他的路线上:
IdHTTP1.get('http://www.google.com/intl/en_ALL/images/logo.gif',MS);
Run Code Online (Sandbox Code Playgroud)
谢谢,克里斯
uses
GIFImg;
procedure TForm1.btn1Click(Sender: TObject);
var
MS : TMemoryStream;
GIf: TGIFImage;
begin
MS := TMemoryStream.Create;
GIf := TGIFImage.Create;
try
IdHTTP1.get('http://www.google.com/intl/en_ALL/images/logo.gif',MS);
Ms.Seek(0,soFromBeginning);
Gif.LoadFromStream(MS);
img1.Picture.Assign(GIF);
finally
FreeAndNil(GIF);
FreeAndNil(MS);
end;
end;
Run Code Online (Sandbox Code Playgroud)
你如何捕获异常?捕获任何其他异常的方式相同.使用try- except块.
procedure TForm1.btn1Click(Sender: TObject);
var
MS : TMemoryStream;
Gif: TGIFImage;
begin
MS := TMemoryStream.Create;
try
Gif := TGIFImage.Create;
try
try
IdHTTP1.Get('http://www.google.com/intl/en_ALL/images/logo.gif', MS);
except
on e: EIdHTTPProtocolException do begin
if e.ErrorCode = 404 then begin
// not found
exit;
end else begin
// some other reason for failure
raise;
end;
end;
end;
MS.Position := 0;
Gif.LoadFromStream(MS);
img1.Picture.Assign(Gif);
finally
Gif.Free;
end;
finally
MS.Free;
end;
end;
Run Code Online (Sandbox Code Playgroud)
当Indy得到不可接受的响应时,它会引发类型异常EIdHTTPProtocolException.它不会为每个可能的失败原因引发不同的异常类,因此请检查ErrorCode属性以获取数字响应.有关各种响应代码的含义,请参阅HTTP规范.
看起来Indy可以配置为通过方法的AIgnoreReplies参数忽略某些响应代码TIdCustomHTTP.DoRequest,但我已经追溯到我今天愿意去的那个参数,所以如果你想了解更多相关信息,请问一个新的问题或有人可以编辑此答案,以更完整的方式替换此段落.
在上面的例子中,我检查了404(未找到)并退出.请确保您不使用MSif Get引发异常,因为它将具有不确定的内容,并且可能不是有效的GIF图像.对于任何其他服务器响应,我重新引发异常,以便调用者可以处理它.你可能想要改变它.任何不是后代的异常EIdHTTPProtocolException都会自动重新引发.不要捕获您不知道如何解决的错误的异常.
| 归档时间: |
|
| 查看次数: |
3909 次 |
| 最近记录: |