如何处理Plack中的错误延迟响应



试图处理延迟响应中的错误。

每次发送[200,['content-type','application/json']并在冲洗诸如这样的其他事情之前遇到了错误

$ w->写(" mydata"(;

$ w-> close((;

我在stdout和stderr中有错误的警告,但是页面一直在加载。

它将加载,直到我停止应用程序或用手停止页面加载。

我如何停止在代码中加载页面,或如何正确处理我使用延迟响应的此类应用中的错误?

Perl版本5.24海带1.02版与电晕一起奔跑。

我们正在处理错误抛出异常:: class。通过try :: Tiny捕获错误。

还尝试了评估和其他事情,但行不通。但是更改了try :: tiny--> trycatc并返回如果有任何错误,但是我需要为每个捕获块写入返回,看起来很糟糕

#!/usr/bin/perl
use strict;
use warnings;
use Kelp::Less;
get '/hello' => sub  {
    return sub {
        my $res = shift;
        my $w = $res->([200, [ 'Content-Type', 'application/json' ]]);
        my $data = 10 / 0;
        $w->write("MyData");
        $w->close();
    }
};
run;

我正在寻找正确的错误处理,我需要尝试{} catch {};在每个可能失败的代码上?

感谢@ikegami的答案,但是在尝试使用Object :: Destoyer和Sub :: ScopeFinalizer之后,页面仍在加载。据我了解,$ W(作者(不会导致页面加载。退出示波器后,$ W到了Undef,然后没有什么可关闭的,这是代码。

#!/usr/bin/perl
use strict;
use warnings;
use Object::Destroyer;
use Kelp::Less;
get '/hello' => sub  {
    return sub {
        my $res = shift;
        my $w = $res->([200, [ 'Content-Type', 'application/json' ]]);
        my $g = Object::Destroyer->new( sub { $w->close if $w } );
        my $zzz = 1 / 0;
        $w->write("DATA");
        $w->close();
    }
};
run;

所以我想出了该解决方案,您怎么看?

#!/usr/bin/perl
use strict;
use warnings;
use Try::Tiny;
use Object::Destroyer;
use Kelp::Less;
get '/hello' => sub  {
    return sub {
        my $res = shift;
        my $w = $res->([200, [ 'Content-Type', 'application/json' ]]);
        my $g = Object::Destroyer->new( sub { $w->close if $w; } );
        my $ans = try {                                                                   
            my $zzz = 1 / 0;                                                              
        }                                                                                 
        catch {
            print $_;                                                                   
            return;                                                                       
        };                                                                                
        return unless $ans;
        $w->write("DATA");
        $w->close();
    }
};
run;

包装应用程序解决此问题
Plack::Middleware::HTTPExceptions

最新更新